flask学习03-RESTful风格用户注册及登录接口开发

发布时间 2023-11-26 22:11:36作者: 一粒梵尘

一、注册接口

class Register(Resource):
def post(self):
    data = request.get_json()  #request.json() 获取到请求的参数,得到一个字典对象
    #print(f'请求入参:{data}')
    username = data.get("username")
    password = data.get("password")
    if not username or not password:
    return jsonify({"code": 111, "msg": "用户名或密码不能为空"})
    if Users.query.filter_by(username=username).first() is not None:
    print('existing user')
    return jsonify({"code": 222, "msg": "账号已存在"})



    with current_app.app_context():
   user = Users(username=username,password=password)
   user.hash_password(password)
   db.session.add(user)
   db.session.commit()

    return {'status':200,'msg':'注册成功!',"data": {"username": username}}
二、登录接口
class Login(Resource):

def post(self):
args = reqparse.RequestParser()\
.add_argument('username', type=str, location='json', required=True, help="用户名不能为空")\
.add_argument("password", type=str, location='json', required=True, help="密码不能为空")\
.parse_args()
print(f"args: {args}")
user = Users.query.filter_by(username=args.get('username')).first()
if not user:
return {"code": 222, "msg": f"用户名或密码不正确"}
else:
if not user.is_active:
return {"code": 333, "msg": f"{user.username} not active"}
else:
# 验证密码
if user.verify_password(args.get('password')):
access_token = create_access_token(identity=user.username)
print(f"access_token:{access_token}")
return jsonify({
"code": "0",
"message": "success",
"data": {
"access_token": access_token,
"userid": user.id
}
})
else:
return {"code": 222, "msg": f"用户名或密码不正确"}