flask十五:(二)RESTful Response

文档:https://flask-restful.readthedocs.io/en/latest/reqparse.html

使用flask_restful里面的reqparse做参数校验

 

from flask_restful import abort, reqparse

from application.models import Goods

parser = reqparse.RequestParser()
parser.add_argument("name", require=True, type=str, help="name,请输入字符串")  # 参数必须
parser.add_argument("price", type=float)  # price参数必须是float
parser.add_argument("haha", action="append")  # haha参数解析为列表
parser.add_argument("__cfduid", dest="cookie_uid", location="cookies")  # 从cookie中获取__cfduid参数,参数使用的别名为cookie_uid
parser.add_argument("__cfduid", dest="cookie_uid_2", action="append", location=["cookies", "args"])  # 从cookie中获取__cfduid参数,参数使用的别名为cookie_uid
parser.add_argument("User-Agent", dest="ua", location="headers")
# 如果没有指定location,则从get,post,form,headers,cookies获取参数

class GoodsResource(Resource):
    @marshal_with(goods_fields)
    def post(self):
        # name = request.form.get("name")
        # price = request.form.get("price")

        args = parser.parse_args()
        name = args.get("name")
        price = args.get("price")

        goods = Goods()
        goods.name = name
        goods.price = price

        if not goods.save():
            abort(http_status_code=400)
        return goods

 

 

 

post请求http://127.0.0.1:5000/goods,假如name为空,reqparse会帮我们抛出提示:help中写的错误。如果help中没有描述,则使用默认的错误内容。


 




 

 

posted on 2020-06-23 11:59  myworldworld  阅读(130)  评论(0)    收藏  举报

导航