Restful视图-参数解析

定义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)

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值