flask-restful基本使用
基本使用
from flask_restful import Api,Resource,reqparse,inputs from flask import Flask,render_template, url_for # 注册 app = Flask(__name__) api = Api(app) # 类继承自Resource class LoginView(Resource): def post(self): return {"username":"zhiliao"} # 这里可字典 api.add_resource(LoginView,'/login/',"/register/") # 可以写多个路由
url_for("loginview") # 注意默认情况下会把类名转换为小写
参数验证
add_argument可以指定这个字段的名字,这个字段的数据类型等。具体参数如下:
1. default:默认值,如果这个参数没有值,那么将使用这个参数指定的值。
2. required:是否必须。默认为False,如果设置为True,那么这个参数就必须提交上来。
3. type:这个参数的数据类型,如果指定,那么将使用指定的数据类型来强制转换提交上来的值。
4. choices:选项。提交上来的值只有满足这个选项中的值才符合验证通过,否则验证不通过。
5. help:错误信息。如果验证失败后,将会使用这个参数指定的值作为错误信息。
6. trim:是否要去掉前后的空格。
其中的type,可以使用python自带的数据类型(但参数必须有一个,例如str等),同时flask_restful.inputs提供了一些特定的数据类型来强制转换。比如一些常用的:
1. url:会判断这个参数的值是否是一个url,如果不是,那么就会抛出异常。
2. regex:正则表达式。
3. date:将这个字符串转换为datetime.date数据类型。如果转换不成功,则会抛出一个异常。
class LoginView(Resource): def post(self): from datetime import date parser = reqparse.RequestParser() parser.add_argument('birthday',type=inputs.date,help='生日字段验证错误!') # 验证是否是日期 parser.add_argument('telphone',type=inputs.regex(r'1[3578]\d{9}')) # 正则验证 parser.add_argument('home_page',type=inputs.url,help='个人中心链接验证错误!') # url验证 parser.add_argument('username',type=str,help='用户名验证错误!',required=True) # parser.add_argument('age',type=int,help='年龄验证错误!') # 验证是否是数字 parser.add_argument('gender',type=str,choices=['male','female','secret']) # 验证是否在选项中 args = parser.parse_args() # 进行验证并返回结果 print(args) return ...
Serialization
通过使用序列化可以将表信息直接转化为json字符串
from flask_restful import marshal_with, Resource, fields class ProfileView(Resource): resource_fields = { 'username': fields.String, 'age': fields.Integer, 'school': fields.String } @marshal_with(resource_fields) def get(self,user_id): user = User.query.get(user_id) return user
序列化属性
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
resource_fields = { 'education': fields.String(attribute='school') } # 表字段为school 但想输出的key 为education
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
resource_fields = { 'age': fields.Integer(default=18) }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class ArticleView(Resource): resource_fields = { 'aritlce_title':fields.String(attribute='title'), 'content':fields.String, 'author': fields.Nested({ # 多对一 'username': fields.String, 'email': fields.String }), 'tags': fields.List(fields.Nested({ # 多对多 'id': fields.Integer, 'name': fields.String })), 'read_count': fields.Integer(default=80) } @marshal_with(resource_fields) def get(self,article_id): article = Article.query.get(article_id) return article
其他
配合蓝图使用
在蓝图中,如果使用`flask-restful`,那么在创建`Api`对象的时候(api = Api(app)),传入蓝图对象。
渲染模板
返回response对象
如果继承了Resource但是又想返回response对象通过@api.representation('text/html')
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from flask import Blueprint,render_template,make_response @api.representation('text/html') def output_html(data,code,headers): # 函数名不需要关联,如果发现继承Resource的视图返回的是response对象会自动找到这里 print(data) # 这个data为render_template传入的index.html # 在representation装饰的函数中,必须返回一个Response对象 resp = make_response(data) return resp class ListView(Resource): def get(self): return render_template('index.html') api.add_resource(ListView,'/list/',endpoint='list')