Parameter verification of flash development skills

Time:2021-6-21

Parameter verification of flash development skills

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

1. Request parameter classification

Generally speaking, the request sent by the front-end contains the following three types of parameters: URL path parameter, URL query parameter, and the most common JSON format data in the front-end and back-end separation development.

  • URL path parameters
/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/')
  • URL query parameters
/v1/user?page=1&pageSize=10

Similar to the key value pair after the question mark in the URL and connected with & is called the URL query parameter

  • Parameters of JSON format
{
    "name": "xiaowang",
    "age": 1
}

Not to mention the parameters of JSON format. The data in JSON format transferred from the header with content type: application / JSON is like this.

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, we will not have redundant parameter check codes 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 following methods are built on the wtforms library and extended. All the original operations of wtforms library are valid 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 exploration (I have limited ability, and may not be able to expand the implementation), using the ordinary wtforms library, I can not accept the complex format of JSON data, only accept the ordinary format of JSON data and URL query parameters for verification.

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

Implementation method, inheriting the form in wtforms library, realizing 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’s an explanation. The__ init__ Method to instantiate an object, first get the common 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_ API () method calls validate () in the parent class for parameter verification. If the verification result does not pass, the error information will be put into MSG and sent to exception class 400 for processing. We have described the exception processing in detail in the last article. If the verification is passed, the verification completed form will be returned.

Use examples

For a request, the URL is

/v1/user?user_id=1

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 there is an error in the verification, 400 will be returned directly to the front end, and the error information will also be returned.

4. For complex JSON format data

The simple use of wtforms library can not realize the processing of complex JSON format data, so in my exploration, I found that there is an extension library of wtforms, called wtforms JSON, which can be realized through this library.

So I extend the original baseform and use 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

Inheriting the above new base class, this form can realize the verification of 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": [
        {
            "Level 1": "Beijing",
            "Level 2": "Chaoyang"
        },
        {
            "Level 1": "Beijing",
            "Level 2": "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 is any error, please point out.


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

GitHub: https://github.com/luyuze95

Recommended Today

[Q & A share the second bullet] MySQL search engine, after watching the tyrannical interviewer!

Hello, I’m younger brother. A few days ago, I shared the second interview question, the interview site of search engine in MySQL. This question is the interview at normal temperature. After reading it, I’m sure you will gain something in terms of database engine If you haven’t read my first share, you can refer to […]