定义Restful的视图
如果使用Flask-Restful,那么定义视图函数的时候,就要继承自flask_restful.Resource类,然后再根据当前请求的method来定义相应的方法。比如期望客户端是使用get方法发送过来的请求,那么就定义一个get方法。类似于MethodView。
注意事项
endpoint是用来给url_for反转url的时候指定。如果不写endpoint,那么将会使用视图的名字的小写来作为endpoint.
参数解析
# @ Time : 2020/5/10 17:16
# @ Author : Ellen
from flask import Flask, template_rendered, url_for
from flask_restful import Api, Resource, reqparse, inputs, fields, marshal_with
app = Flask(__name__)
# 用Api来绑定app
api = Api(app)
class IndexView(Resource):
def get(self):
return {"username": "ellen"}
def post(self):
parse = reqparse.RequestParser()
# type 类型
# help 错误信息
parse.add_argument('username', type=str, help='用户名验证错误', required=True)
parse.add_argument('password', type=str, help='密码错误')
parse.add_argument('age', type=int, help='年龄错误', default=19)
parse.add_argument('gender', type=str, help='性别错误', choices=['male', 'female', 'secret'])
# url regex
parse.add_argument('homepage', type=inputs.url, help='URL地址错误')
parse.add_argument('telphone', type=inputs.regex(r'1[3]\d{9}'), help='手机号码错误')
args = parse.parse_args()
print(args)
return {"info": "登录成功"}
class ArticleView(Resource):
resource_fields = {
'title': fields.String,
'content': fields.String,
# 'tags'
}
# 及使这个参数没有值 也会返回
@marshal_with(resource_fields)
def get(self):
return {"title": "ellen"}
api.add_resource(IndexView, '/', endpoint='index')
api.add_resource(ArticleView, '/article', endpoint='article')
if __name__ == '__main__':
app.run(debug=True)