The implementation of flash restful API and the basic permission control based on flash httpauth

This series of tutorials is divided into four stages

1.flask restful web service

2.flask restful api

3. Flash httpauth realizes authority control

4.uwsgi management flask application



In the previous article, we introduced and studied the related content of implementing restful web services with flash. On this basis, we will develop and study the restful api of flash.

On the web Learning from services, we have learned that the route definition of the flag is defined by the route method after the instantiation of the flag class, but there is a problem that we need to define the route corresponding to this function in each function header. If we write the class method, we need to instantiate it in the route function before realizing the route control, which is obviously not conducive to the development of large projects Routing management.

The characteristics of restful api are as follows:
It can independently maintain the route in the flash. The following are the related modules that this paper will learn from the flash restful API:

from flask import Flask, jsonify, url_for, request
# From flash.ext.restful this module used in the original is not applicable in Python 3
from flask_restful import Api, Resource, fields, marshal, reqparse, abort


Among them, the Flask, jsonify, request and abort modules have been introduced and used in the above, and will not be repeated here.

URL for: route jump module
Api: restful api module
Resource: restful inheritance class
fields: data field customization and reorganization method
marshal: traversal and reorganization of data dictionary with fields
reqparse: retrieve the data in the request to determine whether it meets the requirements


After understanding the relevant module information, the next step is to implement the specific restful api development.
First let's look at a piece of restful api code:

from flask import Flask, request
from flask_restful import Api, Resource, marshal, fields, reqparse

app = Flask(__name__)
# restful interface method
api = Api(app)

class UserApi(Resource):

    def get(self):
        return 'get restful api data'

    def post(self):
        return 'update restful api data'

    def delete(self):
        return 'delete restful api data '

api.add_resource(UserApi, '/users', endpoint='user')

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

Api(app) is a flash ﹣ restful call method. It inherits the Resource class in the UserApi class, indicating that the class is a standard class conforming to the restful api
Api.add'resource is a method to define a route for the UserApi class. The endpoint attribute is an alias defined for this class of route. By default, it will be the same as the class name. In the case of url'for route jump, etc., avoid the problem of too long class name, such as:

return url_for('user')

It will jump to the routing method with endpoint as user.

In the above example code, we can find that there are three functions defined in the UserApi class, namely:

get() corresponds to HTTP get method
post() corresponds to HTTP post method
delete() corresponds to HTTP delete method

When we visit http://localhost/users, we use three methods of HTTP to see the actual effect:
get method:

$ curl -i 'http://localhost:5000/users'
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 23
Server: Werkzeug/1.0.1 Python/3.7.5
Date: Thu, 14 May 2020 02:06:15 GMT
"get restful api data"

post method:

$ curl -i -X POST 'http://localhost:5000/users'
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 26
Server: Werkzeug/1.0.1 Python/3.7.5
Date: Thu, 14 May 2020 02:06:56 GMT
"update restful api data"

delete method:

$ curl -i -X delete 'http://localhost:5000/users'
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 27
Server: Werkzeug/1.0.1 Python/3.7.5
Date: Thu, 14 May 2020 02:07:23 GMT
"delete restful api data "

Above, we can see that in the same route, different access methods correspond to the corresponding function names in the UserApi class, which is a convenience and standard in the restful api. Instead of defining HTTP request methods in the route, we directly define the corresponding functions in the route class UserApi, restful The API will automatically parse the function and handle the return. In large-scale project development, this method is very convenient and efficient, and also improves the code quality and standardization to a certain extent.

The basic development standard of restful api is the method in the above code example. In the actual development, we will write the corresponding data processing methods and request parsing methods in get, post and delete functions. Next, we will learn the unused fields, Marshall and reqparse modules. Let's take a look at a piece of code, which will include the usage of these three modules:

from flask import Flask
from flask_restful import Api, Resource, marshal, fields, reqparse

# Instantiate the flask application
app = Flask(__name__)
# restful interface method
api = Api(app)

users = [
    {
        'id': 1,
        'name': 'mike',
        'age': 18
    },
    {
        'id': 2,
        'name': 'suny',
        'age': 20
    }
]

user_fields = {
    'name': fields.String,
    'age': fields.Integer,
    'url': fields.Url(endpoint='user')
}

class UserApi(Resource):

    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('name', type=str, required=True,
                                   help='No name provided')
        self.reqparse.add_argument('age', type=int, default="")
        super(UserApi, self).__init__()

    def get(self):
        args = self.reqparse.parse_args()
        print(args)
        for k in args:
            if args[k] != None:
                return {'user': args[k]}

    def post(self):
        return {"task": marshal(users, user_fields)}

    def delete(self):
        return 'delete restful api data '

api.add_resource(UserApi, '/users', endpoint='user')

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

Next, we request GET and POST methods respectively to see the return information:

# GET request without parameters:
$ curl -i -X GET 'http://localhost:5000/users'
HTTP/1.0 400 BAD REQUEST
Content-Type: application/json
Content-Length: 42
Server: Werkzeug/1.0.1 Python/3.7.5
Date: Thu, 14 May 2020 02:56:33 GMT

{"message": {"name": "No name provided"}}

# GET request for parameters
$ curl -i -X GET -d 'name=mike' 'http://localhost:5000/users'
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 17
Server: Werkzeug/1.0.1 Python/3.7.5
Date: Thu, 14 May 2020 02:57:04 GMT

{"user": "mike"}

# POST request
$ curl -i -X POST 'http://localhost:5000/users'
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 103
Server: Werkzeug/1.0.1 Python/3.7.5
Date: Thu, 14 May 2020 02:57:25 GMT

{"task": [{"name": "mike", "age": 18, "url": "/users"}, {"name": "suny", "age": 20, "url": "/users"}]}


After observing the results of different request returns, we can find that our request processing of interface parameters and data dictionary reorganization take effect respectively. Using reqparse to retrieve interface parameters saves our own process of judging in request function, simplifies code and improves code quality. fields+marshal module realizes data dictionary reorganization, adds new data and returns .


In practical application, the above modules can effectively improve the development efficiency and code quality. You should further improve the use method on this basis, which will not be expanded here.


Among them, we call the super method in the init function, which is called super class. In the class with class inheritance, we can effectively solve the problem of duplication or attribute modification of the parent child class. Python Super functions


So far, the basic development and learning of the restful api of flash have been completed. Thank you for watching.

Tags: Python curl JSON Attribute

Posted on Thu, 14 May 2020 01:56:03 -0700 by ChibiGuy