This is the 20th day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021.

The view function

In Flask, the route is a mapping between the requested URL and the handler function. The app.route decorator is used to bind the handler function to the URL, and the handler function of the route binding is called a view function.

@app.route('/user/<name>')
def hello_user(name) :
    return 'Hello {}! '.format(name)
Copy the code

The hello_user() function above is a simple view function.

We can also bind the view function to the URL using the app.add_url_rule() method instead of using the app.route decorator, which is also called app.add_url_rule().

def hello() :
    return 'hello Flask! '


app.add_url_rule('/hello', view_func=hello)
Copy the code

You can use the app.add_url_rule() method to separate routes from views, facilitating unified route management.

Class view

Including before we use above, are based on the function of view, it is the most simple and convenient usage, but it is not easy to expand, actually view function can also be based on class to implement, advantage is that kind of support inheritance, can put some common code in the parent class, other subclasses can inherit, in some cases, using class more reasonable, more easy to extend.

The class view is divided into standard class view and scheduling method-based class view, which are described below.

Standard class view

The standard class view is written as follows:

  • The parent class must inherit the flask.views.View class
  • The subclass implementationdispatch_request()Method to complete its own business logic and return results
  • Use a subclassapp.add_url_rule()To register, whichview_funcParameters usingas_view()Method does class method conversions
  • If specified during registrationendpointParameters,endpointOverrides the specified view name, usingurl_forMust be usedendpointThe specified value

The specific usage is as follows:

from flask.views import View


class ParentView(View) :
    def __init__(self) :
        super().__init__()
        # Public part information
        self.public_data = 'Flask Web App'


class Index(ParentView) :
    methods = ['GET']

    def dispatch_request(self) :
        return self.public_data + " index"


class User(ParentView) :
    methods = ['POST']

    def dispatch_request(self) :
        return self.public_data + " user"


app.add_url_rule('/index', endpoint='index', view_func=Index.as_view('index'))
app.add_url_rule('/user', endpoint='user', view_func=User.as_view('user'))
Copy the code

The above code creates a ParentView class inherited from flask.views.View, and then creates Index and User classes inherited from ParentView, and overwrites the dispatch_request() function, respectively. Using the parent class ParentView property public_data, to achieve their own business logic. We then convert the class to the actual view function using the as_view() method, which must pass in a unique and unique view name. The view is then bound to the specified route by the app.add_url_rule() method.

The HTTP request methods supported by the class view are specified by the view class variable methods, and only GET requests are supported by default.

Method-based view

If a view supports multiple HTTP request methods, is there an easier way to do this than to use view functions to execute different business logic for different request methods? Flask.views.MethodView, a subclass of flask.views.View, implements logic processing by specifying a small method with the same name as the request method. Each HTTP method maps to a function with the same name (lowercase). Let’s see how to use it in detail.

from flask.views import MethodView


class UserView(MethodView) :
    def get(self) :
        user_id = request.args.get("user_id")
        return "Hello user:{}".format(user_id)

    def post(self) :
        name = request.form.get("name")
        password = request.form.get("password")
        if name == "admin" and password == "123456":
            return "hello admin!"
        else:
            return "not allow!"

app.add_url_rule('/user/get_info', view_func=UserView.as_view('get'))
app.add_url_rule('/user/login', view_func=UserView.as_view('post'))
Copy the code

The get() function defined in the code is used to handle the GET request, and the POST () function is used to handle the POST request. The code eliminates the judgment statement of the HTTP request method, and is not more RESTFul.

Request tests:

Original is not easy, if small partners feel helpful, please click a “like” and then go ~

Finally, thank my girlfriend for her tolerance, understanding and support in work and life!