Spaces:
Runtime error
Runtime error
File size: 1,121 Bytes
d674f7c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import redis
from flask import Flask, request, jsonify
app = Flask(__name__)
db = redis.Redis(host='localhost', port=6379, db=0)
@app.route('/register', methods=['POST'])
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
@app.route('/login', methods=['POST'])
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)
|