Flask 学习-70.Flask-RESTX 注册接口实例
前言
注册接口主要是密码需要加密,用到werkzeug.security
模块的2个方法generate_password_hash
, check_password_hash
.
数据库操作用到Flask-SQLAlchemy ,相关的基础配置就不写了,这里主要讲注册相关的代码。
models 模型设计
设计Users 表模型
from . import db
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
class Users(db.Model):
"""用户管理"""
__tablename__ = 'user' # 数据库表名
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(50), unique=True, nullable=False)
password = db.Column(db.String(128), nullable=False)
is_active = db.Column(db.Boolean, default=1)
email = db.Column(db.String(64), nullable=True)
create_time = db.Column(db.DateTime, default=datetime.now)
update_time = db.Column(db.DateTime, onupdate=datetime.now, default=datetime.now)
def hash_password(self, password):
"""密码加密"""
self.password = generate_password_hash(password)
def verify_password(self, password):
"""校验密码"""
return check_password_hash(self.password, password)
def __repr__(self):
return f"<Users(id='{self.id}', username='{self.username}'...)>"
def save(self):
"""保存数据"""
db.session.add(self)
db.session.commit()
注册视图
注册功能用到Namespace
from flask_restx import Namespace, Resource, fields, reqparse
from flask import jsonify, request
from .models import Users
from http import HTTPStatus
from werkzeug.exceptions import Conflict, NotFound
api = Namespace('api/v1', description='注册与登录')
# 校验字段
user_model = api.model('UserModel', {
'username': fields.String(
max_length=50, required=True, description='用户名'),
'password': fields.String(
min_length=6, max_length=16, required=True, description='用户登录密码'),
'email': fields.String(max_length=64, description='邮箱')
})
@api.route('/register')
class Register(Resource):
@api.doc(description='注册功能')
@api.expect(user_model, validate=True)
def post(self):
"""register user"""
api.logger.info(f"获取请求参数: {api.payload}")
try:
user = Users(
username=api.payload.get('username'),
email=api.payload.get('email'),
)
# 密码加密后保存
user.hash_password(api.payload.get('password'))
user.save() # 保存数据
return {'message': 'create user success'}, HTTPStatus.CREATED
except Exception as e:
api.logger.error(f"保存注册用户数据报错: {e}")
raise Conflict(f"username {api.payload.get('username')} exists")
主要是对三个入参校验'username,password, email',注册成功不需要对模型序列化,所以这里就不用@api.marshal_with()
.
测试接口
1.先测试注册成功的情况201 CREATED
数据库保存成功
2.参数不合法返回400 BAD REQUEST
3.用户已存在返回409 CONFLICT