(升级)Python+Flask+pymysql实现简单的登录注册
from flask import Flask, request, jsonify
import pymysql
app = Flask(__name__)
# 连接数据库
connection = pymysql.connect(host='localhost',
user='your_username',
password='your_password',
database='your_database',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
@app.route('/register', methods=['POST'])
def register():
data = request.get_json()
username = data['username']
password = data['password']
with connection.cursor() as cursor:
# 创建 SQL 查询语句
sql = "INSERT INTO `users`(`username`, `password`) VALUES (%s, %s)"
cursor.execute(sql, (username, password))
connection.commit()
return jsonify({'message': 'User registered successfully', 'username': username}), 201
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
username = data['username']
password = data['password']
with connection.cursor() as cursor:
# 创建 SQL 查询语句
sql = "SELECT * FROM `users` WHERE `username` = %s AND `password` = %s"
cursor.execute(sql, (username, password))
user = cursor.fetchone()
if user:
return jsonify({'message': 'Logged in successfully', 'username': username}), 200
else:
return jsonify({'message': 'Invalid credentials'}), 401
if __name__ == '__main__':
app.run(debug=True)
在这个示例中,我们使用了pymysql
库来连接MySQL数据库,并且实现了简单的登录和注册功能。这个示例假设你的数据库中有一个名为users
的表,它至少包含username
和password
字段。记得替换数据库连接的host
、user
、password
和database
为你自己的数据库信息。
评论已关闭