You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.5 KiB

10 months ago
from flask import *
from flask_sqlalchemy import SQLAlchemy
import pymysql
10 months ago
import os
from tkinter import filedialog
import pymysql.cursors
DB_HOST = 'localhost' # 数据库主机
DB_USER = 'root' # 数据库用户名
DB_PASSWORD = '123456' # 数据库密码
DB_NAME = 'file' # 数据库名
10 months ago
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@localhost:3306/file'
db = SQLAlchemy(app)
class User(db.Model):
_table_ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50),nullable=False)
password = db.Column(db.String(50),nullable=False)
def query_user(username):
with app.app_context():
return User.query.filter(User.username == username).first()
def add_user(username, password):
with app.app_context():
user = User(username=username, password=password)
db.session.add(user)
db.session.commit()
10 months ago
def create_table():
connection = pymysql.connect(host=DB_HOST, user=DB_USER, password=DB_PASSWORD, db=DB_NAME)
try:
with connection.cursor() as cursor:
cursor.execute(CREATE_TABLE_SQL)
connection.commit()
print("Table 'images' created successfully.")
finally:
connection.close()
def path_to_bytes():
return filedialog.askopenfilename(filetypes=(("Image Files", "*.jpg;*.png;*.gif"), ("All Files", "*.*")))
def upload_image():
selected_image_path = path_to_bytes()
if selected_image_path:
with open(selected_image_path, 'rb') as image_file:
image_content = image_file.read()
connection = pymysql.connect(host=DB_HOST, user=DB_USER, password=DB_PASSWORD, db=DB_NAME)
try:
with connection.cursor() as cursor:
sql = "INSERT INTO images (filename, content) VALUES (%s, %s)"
cursor.execute(sql, (os.path.basename(selected_image_path), pymysql.Binary(image_content)))
connection.commit()
print(f"Image '{selected_image_path}' uploaded successfully.")
finally:
connection.close()
CREATE_TABLE_SQL = """
CREATE TABLE IF NOT EXISTS images (
id INT AUTO_INCREMENT PRIMARY KEY,
filename VARCHAR(255),
content LONGBLOB,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
10 months ago
try:
with app.app_context():
# 尝试连接数据库
db.create_all()
print("数据库连接成功!")
except Exception as e:
print(f"数据库连接失败: {str(e)}")