12. Flask-Restful defines the view of Restful. Parameter certification standardization return parameters

12. Flask-Restful defines the view of Restful. Parameter certification standardization return parameters

Define the view of Restful

 Installation: pip install flask-restful

 If you use Flask-restful, then when defining the view function, you must inherit the flask_restful.Resourse class, and then define the corresponding method according to the currently requested method. For example, if the client is expected to use the get method to send a request, then a get method is defined.

from flask import Flask
from flask_restful import Api,Resource

app = Flask(__name__)
api = Api(app) #Use Api to bind app

class LoginView(Resource):
    def post(self):
        return {'username':'derek'}
api.add_resource(LoginView,'/login/',endpoint="login")

@app.route('/')
def index():
    return'Hello World!'

if __name__ =='__main__':
    app.run(debug=True)

Description:

  • Import an API from flask_restful to create an api object.
  • Write a view function, let it inherit from Resource, and then define the corresponding method.
  • The endpoint is used to specify when url_for reverses the url. If the endpoint is not written, the lowercase of the name of the view function will be used as the endpoint.
  • The second parameter of add——resource is the url to access the view function. This url is the same as the previous route. Parameters can be passed. The other difference is that this method can pass multiple urls to specify the view function.
  • If you want to return json data, then use flask_restful. If you want to render a template, use the previous method.

 Parameter authentication

 The Flask-Restful plugin provides a package similar to WTForms to verify the validity of the submitted data, called reqparse.

from flask import Flask
from flask_restful import Api,Resource,reqparse,inputs

app = Flask(__name__)
api = Api(app)

class LoginView(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username',type=str,help='username verification error',default='xxx',trim=True)
        parser.add_argument('password',type=str,help='password verification error', required=True)
        parser.add_argument('gender',type=str,choices=['male','famale'])
        parser.add_argument('home_page',type=inputs.url,help=('personal center link error'))
        parser.add_argument('birthday',type=inputs.date)
        args = parser.parse_args()
        print(args)
        return {'username':'derek'}

api.add_resource(LoginView,'/login/',endpoint="login")

@app.route('/')
def index():
    return'Hello World!'

if __name__ =='__main__':
    app.run(debug=True)

Parameter Description:

  • default: The default value. If this parameter has no value, the value specified by this parameter will be used.
  • required: Is it necessary? The default is False, if it is set to True, then this parameter must be submitted.
  • type: The data type of this parameter. If specified, the specified data type will be used to force the submitted value.
  • choices: options. The submitted value only meets the value in this option, otherwise the verification fails.
  • help: Error information. If the verification fails, the value specified by this parameter will be used as the error message.
  • trim: Whether to remove the leading and trailing spaces.

 For the type, you can use some data types that come with python, or you can use some specific data types under flask_restful.inputs to force conversion. For example, some commonly used:

  • url: It will be judged whether the value of this parameter is a url, if not, an exception will be thrown.
  • regex: regular expression.
  • date: Convert this string to datetime.date data type. If the conversion is not successful, an exception will be thrown.

Standardized return parameters

Output field

 For a view function, you can specify some fields for return. When the orm model or a custom model can be used in the future, it will automatically obtain the corresponding fields of the model, generate json data, and then return it to the client. Which needs to import flask_restful.marshal_with decorator. And a dictionary is needed to indicate the field to be returned and the data type of the field.

 Simple example:

from flask_restful import Resource,fields,marshal_with

class ProfileView(Resource):
    resource_fields = {
        'username':fields.String,
        'age':fields.Integer
        'school':fields.String
    }
    @marshal_with(resource_fields)
    def get(self,user_id):
        user = User.query.get(user_id)
        return user

In the get method, when returning user, flask_restful will automatically read the username and age attributes on the user model. Form a string in json format and return it to the client.

Rename attribute

Many times your public-facing field names are different from the internal attribute names. Use attributes to configure this mapping. For example, if you want to return the value of user.sckool, but when it is returned to the outside, you want to return it with education, then you can write:

  resource_fields = {
        'username':fields.String,
        'age':fields.String
        'education':fields.String(attribute='school') #Rename attribute
    }

Defaults

When returning some fields, sometimes there may be no value, then you can give a default value when specifying the fields.

resource_fields = {
        'username':fields.String,
        'age':fields.Integer(default=18), # default value
        'education':fields.String(attribute='school')    
    }

Complex structure

Sometimes you want to have a more complicated structure in the returned data format. Then you can use some special fields to achieve. For example, if you want to prevent a list in a field, you can use fields.list; for example, if there is a dictionary under a field, you can use fields.Nested.

Simple example:

 resource_fields = {
        'username':fields.String,
        'age':fields.Integer(default=18), # default value
        'education':fields.String(attribute='school'), #renaming attribute
        'tags':fields.List(fields.String),
        'more':fields.Nested({
            'signature':fields.String
        })
    }
Reference: https://cloud.tencent.com/developer/article/1172862 12. Flask-Restful defines the view of Restful Parameter certification standardization return parameters-Cloud + Community-Tencent Cloud