Optimizing flag input parameter verification using pre request

When using flash to implement Restful interface, the request parameters need to be verified to determine whether they comply with specific rules. This article describes how to optimize the verification logic through the pre request library.

Interface requirements

Suppose we need to implement an interface to collect personal information filled in by users. The specific requirements of the interface are as follows:

  1. Interface path: / user/info/new
  2. Interface fields:
fieldtypeexplain
userNamestringUser nickname, required, 2-20 character string
genderintUser gender, required, 1-male, 2-female
ageintUser age, required, an integer between 18 and 60
countrystringUser's nationality; optional; default to China; string length > 2

Interface implementation

If the above interface is not implemented with the help of any third-party tools, the code may be as follows:

from flask import request, Flask


app = Flask(__name__)


@app.route("/user/info/new", methods=["POST"])
def user_info_handler():
    # 1. Judge whether the user name parameter is legal
    user_name = request.form.get("userName")
    if not user_name or not isinstance(user_name, str):
        return "Please fill in the correct user name"
    if len(user_name) < 2 or len(user_name) > 20:
        return "Incorrect length of user name"

    # 2. Judge whether the user's gender parameter is legal
    gender = request.form.get("gender")
    if not gender:
        return "Please fill in user gender"
    try:
        gender = int(gender)
    except ValueError:
        return "Incorrect user gender format"
    if gender not in [1, 2]:
        return "User gender parameter must be[1, 2]between"

    # 3. Judge whether the user grade parameter is legal
    age = request.form.get("age")
    if not age:
        return "Please fill in the user's age"
    try:
        age = int(age)
    except ValueError:
        return "Incorrect user age format"
    if age < 18 or age > 60:
        return "The age must be 18-60 between"

    # 4. Judge whether the nationality is legal
    country = request.form.get("country", "China")
    country = str(country)
    if len(country) < 2:
        return "Illegal length of nationality name"
    
    # TODO: user information registration logic
    return "Success"


if __name__ == "__main__":
    app.run(port=8080)
Copy code

As shown in the above code, in order to ensure that the data stored in the database meets the design requirements, developers need to do a lot of verification work on the input parameters. If they are careless, they may leave hidden vulnerabilities for the system.

Use pre request to check the input parameters

To implement the above interface requirements, let's take a look at how to mask a large number of repeated verification logic through pre request.

from flask import Flask
from pre_request import pre, Rule


app = Flask(__name__)


rule = {
    "userName": Rule(type=str, required=True, gte=3, lte=20, dest="user_name"),
    "gender": Rule(type=int, required=True, enum=[1, 2]),
    "age": Rule(type=int, required=True, gte=18, lte=60),
    "country": Rule(type=str, required=False, gte=2, default="China")
}


@app.route("/user/info/new", methods=["POST"])
def user_info_handler():
    params = pre.parse(rule=rule)
    # TODO: user information registration logic
    return "Success"


if __name__ == "__main__":
    app.run(port=8080)
Copy code

As shown above, the complex parameter verification becomes the preparation of verification rules, pre The parse function will automatically capture the request parameters and judge whether they comply with the verification rules. If they do not comply with the verification rules, an error response will be generated automatically, and the user does not need to do any processing.

Pre request related links

Of course, if you think the above methods are too cumbersome and complex, then OK, you can add 122098892, a poultry nest in me. This is a self-study room. It has just opened and there are no people, but it is a good place for everyone to share experience and resources. Even if you don't want to work overtime late at night, you can find someone to chat!! Look forward to your joining!


 

Keywords: Python

Added by rewast on Mon, 24 Jan 2022 01:24:56 +0200