Spaces:
Runtime error
Runtime error
import redis | |
from flask import Flask, request, jsonify | |
app = Flask(__name__) | |
db = redis.Redis(host='localhost', port=6379, db=0) | |
def register(): | |
data = request.get_json() | |
username = data['username'] | |
password = data['password'] | |
# 检查用户名是否已存在 | |
if db.exists(username): | |
return jsonify({'message': 'Username already exists'}), 400 | |
# 在 Redis 中保存用户名和密码 | |
db.hset(username, mapping={'password': password}) | |
return jsonify({'message': 'User registered successfully'}), 201 | |
def login(): | |
data = request.get_json() | |
username = data['username'] | |
password = data['password'] | |
# 获取保存在 Redis 中的密码 | |
saved_password = db.hget(username, 'password') | |
# 检查用户名和密码是否匹配 | |
if saved_password is None or saved_password.decode() != password: | |
return jsonify({'message': 'Invalid username or password'}), 401 | |
return jsonify({'message': 'Login successful'}) | |
if __name__ == '__main__': | |
app.run(debug=True) | |