前言
model 中有枚举类型字段使用示例
模型设计
class Teachers(db.Model):
__tablename__ = 'teacher' # 数据库表名
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(50), unique=True, nullable=False)
size = db.Column(db.Enum("SMALL", "MEDIUM", "LARGE"), default="MEDIUM")
address = db.Column(db.String(150), nullable=True)
def save(self):
"""保存数据"""
db.session.add(self)
db.session.commit()
def __repr__(self):
return f"<Teachers(id='{self.id}', name='{self.name}'...)>"
同步到数据库
flask db migrate
flask db upgrade
同步后数据库里面可以看到 size 字段是枚举类型
校验枚举类型
请求入参校验枚举类型, 添加enum 参数
teacher_model = api.model('TeacherModel', {
'name': fields.String(
max_length=50, required=True, description='姓名'),
'size': fields.String(
enum=["SMALL", "MEDIUM", "LARGE"], required=False, description='型号'),
'address': fields.String(max_length=150, description='邮箱')
})
视图
@api.route('/teacher')
class TeacherView(Resource):
@api.doc(description='新增老师')
@api.marshal_with(teacher_model)
@api.expect(teacher_model, validate=True)
def post(self):
"""
add teacher
"""
api.logger.info(f"获取请求参数: {api.payload}")
t = Teachers(
name=api.payload.get('name'),
size=api.payload.get('size'),
address=api.payload.get('address'),
)
t.save() # 保存数据
return t, HTTPStatus.CREATED
测试接口
POST http://127.0.0.1:5000/api/v1/teacher HTTP/1.1
User-Agent: Fiddler
Host: 127.0.0.1:5000
Content-Length: 33
Content-Type: application/json
{"name": "yoyo", "size": "SMALL"}
HTTP/1.0 201 CREATED
Content-Type: application/json
Content-Length: 65
Server: Werkzeug/2.0.2 Python/3.8.5
Date: Thu, 22 Sep 2022 01:22:52 GMT
{
"name": "yoyo",
"size": "SMALL",
"address": null
}
参数不合法,返回400 BAD REQUEST