Parameter verification of flash development skills wtforms wtforms JSON

Parameter verification of flash development skills

I usually use or learn some flash development skills in development. I need to have a solid foundation of flash.

1. Request parameter classification

Generally speaking, the request sent by the front end roughly includes the following three types of parameters: url path parameters, url query parameters, and the most common json format data in front and back-end separation development.

  • url path parameter
/v1/user/1

The url path parameter is similar to the parameter in the above example. It is directly carried in the url path and can be changed. Flash has directly provided support for this parameter, for example:

@app.route('/v1/user/<int:id>')
  • url query parameters
/v1/user?page=1&pageSize=10

Similar to this key value pair after the question mark in the url, and the parameters connected with & are called url query parameters

  • Parameters in json format
{
    "name": "xiaowang",
    "age": 1
}

Not to mention the parameters in json format. The header contains content type: Application/json data in json format transmitted from it.

2. Libraries used by the solution

Here, in order to solve the problem of parameter verification, we must extract the part of parameter verification, hide the specific process of parameter verification according to the idea of object-oriented, and give it to a specific class to solve. In this way, there will be no redundant parameter verification code in the view function, which will make the whole view function short and easy to read.

Here we need to install two libraries

pip install WTForms
pip install WTForms-JSON

The subsequent methods are built on the wtforms library and extended. All the original operations of the wtforms library are effective and can continue to be used. If you are not familiar with wtforms, you need to learn it first.

3. For url query parameters and general json format

First of all, after my research (my ability is limited and may not be able to expand the implementation), using the ordinary wtforms library can not accept json data in complex format, but can only accept json data in ordinary format and url query parameters for verification.

  • Examples of json parameters in common format
{
    "name": "xiaowang",
    "age": 1,
    "address": "beijing"
}
  • Examples of json parameters in complex format
{
    "category": {
        "category_name": "computer",
        "category_id": 2
    },
    "address_list": [
        "beijing",
        "shanghai"
    ]
    "name": "xiaohong",
    "age": 1,
}

The implementation method inherits the Form in the wtforms library and implements its own base class parameter verification class BaseForm

class BaseForm(Form):
    def __init__(self):
        data = request.get_json()
        args = request.args.to_dict()
        super(BaseForm, self).__init__(data=data, **args)

    def validate_for_api(self):
        valid = super(BaseForm, self).validate()
        if not valid:
            raise ParameterException(msg=self.errors)
        return self

Here is a description. When instantiating an object with the init method of BaseForm, first get the ordinary json data and query parameter args through the request object in flash, and initialize the parameters by calling the method of the parent class.

And validate_ for_ The API () method calls validate() in the parent class for parameter verification. If the verification result fails, put the error information into msg and send it to the exception class 400 for processing. The exception processing has been described in detail in the previous article. If the verification passes, the form after verification is returned.

Use examples

For a request, the url is

/v1/user?user_id=1

The request body is

{
    "username": "xiaoming",
    "age": 1
}

Then use the following classes:

class UserForm(BaseForm):
    user_id = IntegerField()
    username = StringField()
    age = IntegerField()


form = UserForm().validate_for_api()

The parameter verification can be completed. If the verification is wrong, it will directly return 400 to the front end, and the error message will also be returned.

4. For complex json format data

Simply using wtforms library can not realize the processing of complex json format data, so after my exploration, I found that there is another wtforms extension library called wtforms json, which can be realized through this library.

So I extended the original BaseForm and used wtforms JSON to imitate the original base class. The new base class I implemented is as follows.

import wtforms_json

class JsonForm(Form):

    @classmethod
    def init_and_validate(cls):
        wtforms_json.init()
        form = cls.from_json(request.get_json())
        valid = form.validate()
        if not valid:
            raise ParameterException(msg=form.errors)
        return form

Inherit the above new base class, so that the Form can verify the data in any json format.

Use examples

For a request, if the request body is

{
    "username": "xiaochen",
    "age": 1,
    "address_list": [
        "beijing",
        "shanghai"
    ],
    "info": {
        "name": "hi",
        "length": 5
    },
    "area_list": [
        {
            "level1": "Beijing",
            "level2": "Sunrise"
        },
        {
            "level1": "Beijing",
            "level2": "Haidian"
        }
    ]
}

The verification can be realized through the following Form

class InfoForm(JsonForm):
    name = StringField()
    length = IntegerField()

class AreaForm(JsonForm):
    level1 = StringField()
    levle2 = StringField()

class DemoForm(JsonForm):
    username = StringField()
    age = IntegerField()
    address_list = FieldList(
        StringField(),
        min_entries=1
    )
    info = FormField(InfoForm)
    area_list = FieldList(
        FormField(AreaForm),
        min_entries=1
    )


form = DemoForm().init_and_validate()

In this way, the verification of complex json data can be realized

About the parameter verification of flash, the above are some skills I have mastered at present. If there are errors, you are welcome to point out.

Forward from:

Blog Park: https://www.cnblogs.com/luyuze95/

GitHub: https://github.com/luyuze95

Keywords: Python Flask

Added by monkeybidz on Wed, 09 Feb 2022 17:11:20 +0200