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.

52 lines
1.4 KiB

3 weeks ago
from flask import Flask, request, jsonify
from flask_mysqldb import MySQL
import MySQLdb.cursors
app = Flask(__name__)
# MySQL 配置
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root' # 替换为你的 MySQL 用户名
app.config['MYSQL_PASSWORD'] = 'lin556688' # 替换为你的 MySQL 密码
app.config['MYSQL_DB'] = 'mydatabase'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
# 添加消息和照片
@app.route('/message', methods=['POST'])
def add_message():
message = request.form['message']
photo = request.files['photo']
# 读取照片内容
photo_data = photo.read()
# 插入数据到 MySQL
cursor = mysql.connection.cursor()
cursor.execute("INSERT INTO messages (message, photo) VALUES (%s, %s)", (message, photo_data))
mysql.connection.commit()
cursor.close()
return jsonify({'status': 'success'}), 201
# 获取所有消息
@app.route('/messages', methods=['GET'])
def get_messages():
cursor = mysql.connection.cursor()
cursor.execute("SELECT id, message, created_at FROM messages") # 不直接查询照片以提高性能
result = cursor.fetchall()
cursor.close()
messages = []
for row in result:
messages.append({
'id': row['id'],
'message': row['message'],
'created_at': row['created_at']
})
return jsonify(messages)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)