Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Python webargs module

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, the editor will share with you the relevant knowledge points about how to use the Python webargs module. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

Webargs is a Python library for parsing and validating HTTP request objects, with built-in support for popular web frameworks, including Flask, Django, Bottle, Tornado, Pyramid, webapp2, Falcon, and aiohttp.

First, install python3-m pip install webargs

Document

Basic characteristics # encoding=utf-8from flask import Flaskfrom webargs import fieldsfrom webargs.flaskparser import use_argsapp = 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) 2.1. Use 2.1.1 through the decorator @ use_args ({"name": fields.Str (required=True), "age": fields.Int (required=True),}, location='query')

The first parameter is the definition of the field name, type, required, etc.

Location refers to where to obtain these parameters. Default is json. Optional:

'querystring' (same as' query')

'json'

'form'

'headers'

'cookies'

'files'

After parsing, put all the parameters in the dictionary and pass them to the lower-level function

2.1.2 through the function args = parser.parse (user_args, request)

The parameter is the same as the decorator, with an extra request.

2.2 parameters check from webargs import fields, validateargs_1 = {# required parameters String type "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 (),}

Fields.Str represents the receive string parameter

Required=True means must pass.

Validate=lambda p: len (p) > = 6 indicates a custom check function. Arguments are passed to the function, which returns True to indicate that the check passes, or returns False or throws an exception to indicate that the check fails.

If you want to jointly check multiple parameters, you need to frame the validate parameter in the decorator layer: @ use_args (args_1, validate=lambda args: len (args ["username"]) < len (args ["password"]))

The exception needs to be the from webargs import ValidationError exception, otherwise it will be handled as a program exception

You can also use the built-in check function in the validate library

Missing=10 indicates that if there is no input parameter, set it to the default value.

Fields.List (fields.Str ()) represents a column phenotypic parameter, and the element of the list is a string

Fields.DelimitedList (fields.Str ()) represents a comma-shaped list parameter

Data_key= "user-type" indicates that the field name is modified. The input parameter is user-type, which will be changed to user_type in the args dictionary.

Fields.DateTime (required=True, format='%Y-%m-%d% X') indicates the received date type, and the format needs to match. The parameter value will be converted to datetime type.

"bool": fields.Bool () represents a Boolean type, which can be recognized by 1, 0, 0, true, and false.

Fields.Email () only receives email, and it is estimated that there will be a regular check in it.

Fields.IP () only receives IP

Fields.Constant (constant='COMMON_TYPE') constant parameter. No matter what the value of the input parameter is, type is always equal to COMMON_TYPE.

Fields.Decimal () is converted to Decimal type

Fields.Float () is converted to float type

Fields.URL () fields.UUID () regular check url format or uuid format

Fields.Raw does not check parameter types

Built-in parameter check

Validate=validate.Length (min=1,max=10) checks that the string length needs to be in a certain interval

The validate=validate.OneOf (['male',' female']) input parameter needs to be in the enumeration

2.3 check failure handling

If the parameter check fails, a 422 response is returned, but there is no indication of which parameter is problematic. We can catch this exception through Flask's exception handling mechanism, and then construct the return we want.

@ app.errorhandler (422) # captures outliers @ 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']})

Get information from err. Headers does not know what is the use. Message will have abnormal information, for example, if it does not meet the validate=validate.Length (min=6) check, it will return {'json': {' password': ['Shorter than minimum length 6.']}}.

If the ValidationError exception is actively thrown, the message will contain the contents of the ValidationError exception

We can return this parameter check information to the front end to indicate which parameter is wrong.

The json of messages ['json'] is the key of location

2.4 nested parameters

For some complex, multiple nested parameters

Name: fields.Nested ({"first": fields.Str (required=True), "last": fields.Str (required=True)})

Indicates that name is a nested parameter, that is, a dictionary

Then you need first key and last key in it.

III. Advanced Features 3.1 Custom location

It is said above that location supports query,json and can also be customized.

@ 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 dataparser.location =' data' # set the default location to data

A location of data is defined above, which combines args and json input parameters.

Change the default location to data

You can also do this. This is the official recommendation:

@ 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) 3.2 define schema

In addition to defining args through a dictionary, you can also use classes:

From marshmallow import Schemaclass UserSchema (Schema): name = fields.Str (required=True) age = fields.Int () @ app.route ("/") @ use_args (UserSchema ()) def index1 (args): print ('args', args) return "Hello" 3.3 undefined parameter handling

If the input parameter has undefined parameters, webargs will throw a 422 exception by default.

From webargs.flaskparser import parserimport marshmallowparser.unknown = marshmallow.EXCLUDE # if there are undefined parameters, do not throw args parameters, do not throw exceptions parser.unknown = marshmallow.INCLUDE # if there are undefined parameters, put them into args parameters, do not throw exceptions

You can modify the parse.unknown to modify the policy.

You can also precisely set unknown policies for different location

3.4 Flask's url parameter @ app.route ("/ /") @ use_args (UserSchema ()) def index1 (args, id): print ('args', args, id) return "Hello"

If you need to use the url parameter of Flask, you need to pass the parameter like this

These are all the contents of the article "how to use the Python webargs Module". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report