时间:2022-05-16 08:46:05 | 栏目:Python代码 | 点击:次
webargs是一个用于解析和验证HTTP请求对象的Python库,内置了对流行web框架的支持,包括Flask、Django、Bottle、Tornado、Pyramid、webapp2、Falcon和aiohttp。下面看下Python webargs 模块详解。
python3 -m pip install webargs
# encoding=utf-8 from flask import Flask from webargs import fields from webargs.flaskparser import use_args app = Flask(__name__) app.route("/") @use_args({ "name": fields.Str(required=True), "age": fields.Int(required=True), }, location='query') def index(args): print('args', args) return "Hello " + args["name"] if __name__ == "__main__": app.run(debug=1)
@use_args({ "name": fields.Str(required=True), "age": fields.Int(required=True), }, location='query')
解析完后,把所有参数放在字典里面,传给下层函数
args = parser.parse(user_args, request)
参数和装饰器一样,多了一传request
from webargs import fields, validate args_1 = { # 必须参数,字符串类型 "username": fields.Str(required=True), # validate "password": fields.Str(validate=lambda p: len(p) >= 6), "password": fields.Str(validate=validate.Length(min=6)), # Default value when argument is missing "display_per_page": fields.Int(missing=10), # Repeated parameter, e.g. "/?nickname=Fred&nickname=Freddie" "nickname": fields.List(fields.Str()), # Delimited list, e.g. "/?languages=python,javascript" "languages": fields.DelimitedList(fields.Str()), # When value is keyed on a variable-unsafe name # or you want to rename a key "user_type": fields.Str(data_key="user-type"), "start_day": fields.DateTime(required=True, format='%Y-%m-%d %X'), "bool": fields.Bool(), "email": fields.Email(), "ip": fields.IP(), "type": fields.Constant(constant='COMMON_TYPE'), "money": fields.Decimal(), "weight": fields.Float(), "url": fields.URL(), "uuid": fields.UUID(), "raw": fields.Raw(), }
内置参数检查
如果参数检查失败,会返回422响应,但是不会提示哪个参数有问题。我们可以通过Flask的异常处理机制,捕获这个异常,然后构造我们想要的返回
@app.errorhandler(422) # 捕获422和400的异常码 @app.errorhandler(400) def handle_error(err): headers = err.data.get("headers", None) messages = err.data.get("messages", ["Invalid request."]) print(headers) print(messages) # {'json': {'password': ['Shorter than minimum length 6.']}} return json.dumps({'err_code': 10000, 'err_msg': messages['json']})
validate=validate.Length(min=6)
检查,就会返回{'json': {'password': ['Shorter than minimum length 6.']}}
messages['json']
的json是location的key对于一些复杂的,有多重嵌套的参数
"name": fields.Nested( {"first": fields.Str(required=True), "last": fields.Str(required=True)} )
上面说了location支持query,json这些,也可以自定义
@parser.location_loader("data") def load_data(request, schema): data = {} data.update({k: request.args.get(k) for k in request.args}) if request.json: data.update({k: request.json.get(k) for k in request.json}) print(data, 'dataaaaa') return data parser.location = 'data' # 设置默认的location为data
也可以这样,这个是官方推荐方法:
@parser.location_loader("args_and_json") def load_data(request, schema): from webargs.multidictproxy import MultiDictProxy newdata = request.args.copy() if request.json: newdata.update(request.json) return MultiDictProxy(newdata, schema)
除了可以通过字典定义args,也可以通过类:
from marshmallow import Schema class UserSchema(Schema): name = fields.Str(required=True) age = fields.Int() @app.route("/") @use_args(UserSchema()) def index1(args): print('args', args) return "Hello "
如果入参有未定义的参数,webargs默认会抛出422异常
from webargs.flaskparser import parser import marshmallow parser.unknown = marshmallow.EXCLUDE # 如果有未定义参数,不放到args参数,不抛异常 parser.unknown = marshmallow.INCLUDE # 如果有未定义参数,放到args参数,不抛异常
@app.route("/<int:id>/") @use_args(UserSchema()) def index1(args, id): print('args', args, id) return "Hello "
如果需要用到Flask的url参数,就需要这样传递参数