Flask_ View functions and view classes

1 View function

We have learned about the general usage of view functions before. In this section, we will learn more about view functions

1.1 introduction to endpoint

The endpin parameter is a parameter written in the decorator of the registered route. Its scientific name is endpoint. We can understand it as an alias of a function. It turns out that when we flip the url of the view function, we directly pass the name of the function, such as url_for('function name '), now we can specify an endpoint='fbv' parameter to flip the url. If you do not specify an endpoint, the function name is used as the endpoint name by default.
example:

@app.route('/fbvtest/',methods=['GET','POST'],endpoint='fbv')  
def fbvtest():
    url_demo = url_for('fbv')
    return 'Flipping with view function alias url Is:{}'.format(url_demo)

key word:

  • You can freely specify the endpoint name and URL by using the endpoint='fbv 'parameter of @ app.route()_ For can flip according to the specified endpoint name.

1.2 analysis of decorator registration routing source code

(1) First write a small view function

#Principle of registered decorator
#1 v = app.route('/source_code_demo/',endpoint='source_code')
#2 v(source_code_demo)
@app.route('/source_code_demo/',endpoint='source_code')
def source_code_demo():

    return 'source_code_demo'

(2) View the source code of app.route()

... 
    def route(self, rule, **options):
    ...
         def decorator(f):
                endpoint = options.pop('endpoint', None)
                self.add_url_rule(rule, endpoint, f, **options)
                return f
            return decorator

Resolution:

  • , it is found that route() returns the address of the decorator function. Then, based on the principle of syntax sugar and decorator, the decorator will run in parentheses, such as decorator(source_code_demo)

  • In the decorator function, first take out the endpoint, and then run self.add_url_rule(rule, endpoint, f, **options)

  • So self.add_url_rule(rule, endpoint, f, **options) is the core of registered routing

(3) Click self.add_url_rule(rule, endpoint, f, **options) to view the source code,
Click in again_ endpoint_from_view_func(view_func) view the source code

...
    
  @setupmethod
  def add_url_rule(self, rule, endpoint=None, view_func=None,
                     provide_automatic_options=None, **options):
        
  ...

  	   if endpoint is None:
            endpoint = _endpoint_from_view_func(view_func)
        options['endpoint'] = endpoint
        methods = options.pop('methods', None)

        # if the methods are not given and the view_func object knows its
        # methods we can use that instead.  If neither exists, we go with
        # a tuple of only ``GET`` as default.
        if methods is None:
            methods = getattr(view_func, 'methods', None) or ('GET',)
            
        ...

def _endpoint_from_view_func(view_func):
    """Internal helper that returns the default endpoint for a given
    function.  This always is the function name.
    """
    assert view_func is not None, 'expected view func if endpoint ' \
                                  'is not provided.'
    return view_func.__name__

Resolution:

  • From the above code, we can until if no endpoint is specified, we call_ endpoint_from_view_func()

  • Observe_ endpoint_from_view_func function we can know that it returns the name of the view function and assigns a value to the endpoint

  • The default value ('GET ') will be assigned to the methods if they are not specified

Summary:

  1. self.add_url_rule(rule, endpoint, f, options) is the core of registered routing
  2. Observe_ endpoint_from_view_func function we can know that it returns the name of the view function and assigns a value to the endpoint
  3. Methods is not specified. A default value ('GET ') will be assigned to methods

1.3 another way to register routes - app.add_url_rule()

By looking at the source code written in the previous section, we now know that the core of app.route() is self.add_url_rule(rule, endpoint, f, options) is the core of registered routing. So we can use app. Add directly_ url_ Rule () to register the route.
example:

def add_url_test():

    return 'Realized add_url Register route by'
                 # url endpoint function address
app.add_url_rule('/add_url_test/',endpoint='add_demo',view_func=add_url_test)

1.4 add custom decorator in view function

In our usual development process, many functions requiring permission verification need to use decorators. The following code is how to implement a decorator in flash.

from flask import Flask, request
from functools import  wraps

app = Flask(__name__)

def login_verify(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        user_name = request.args.get('user')
        password = request.args.get('password')
        if user_name == 'mark' and password == '123':
            return func(*args,**kwargs)
        else:
            return 'Please login'
    return wrapper

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

@app.route('/my_info/')
@login_verify
def my_info():
    return 'Personal information page'

key word:

  1. The decorator must be written below the registered route and above the view function.
  2. The @ wraps(func) method must be used inside the decorator to protect the properties of the decorated function.

2 view class

2.1 basic writing method of view class

from flask import Flask, views, request, url_for
from functools import wraps

def login_verify(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        user_name = request.args.get('user')
        password = request.args.get('password')
        if user_name == 'mark' and password == '123':
            return func(*args,**kwargs)
        else:
            return 'Please login'
    return wrapper


class CBVTest(views.MethodView):

    methods = ['GET','POST']  # What are the methods for specifying which can be received
    decorators = [login_verify,]  # Specifies a custom decorator

    def get(self):
        print(url_for('cbvtest'))
        return 'cbv_get'
    def post(self):
        return 'cbv_post'
app.add_url_rule('/cbvtest',view_func=CBVTest.as_view(name='cbvtest'),endpoint='end_demo')

Explanation:

  1. First, import views from flash

  2. When writing a class, you must inherit views.MethodView

  3. Write methods = ['GET','POST'] in the class to specify the acceptable request type

  4. Write decorators = [login_verify,] in the class to specify decorators. The first decorator is the innermost function, which is wrapped back in turn

  5. Write def get(self) in the class: used to get the get request

  6. Write def post(self) in the class: used to get the post request

  7. Method of adding route
    app.add_url_rule(
    'routing', view_func=CBVTest.as_view(name = "customize an endpoint name"))

The principle is CBVTest.as_view(name = 'customize an endpoint name') will return a function. Name is the name of the function. You can use this function to distribute requests and other operations.

3. Explain the parameters of registered route in detail:

Common parameters

@app.route and app.add_url_rule parameter:
rule, URL rule
view_func, View function name
endpoint = None, Name for reverse build URL,Namely: url_for('name')
methods = None, Allowed request methods, such as:["GET", "POST"]

Uncommon parameters (understand)

(1) Is the / symbol at the end of the URL strict_slashes = False

strict_slashes = False
    '''
        @app.route('/index', strict_slashes=False)
        #visit http://www.xx.com/index/  or http://www.xx.com/index All right
        @app.route('/index', strict_slashes=True)
        #Access only http://www.xx.com/index
    '''

(2) Redirect to the specified address_ to=“ ”

@app.route("/",redirect_to='/home/')
def index():

    return 'Root path'

@app.route("/home/")
def admin_demo():

    return 'home route'

(3) Provide default parameter values for functions

defaults = None, Default value, When URL There are no parameters in the function. When the function needs parameters, use defaults = {'k': 'v'}

**(4) * * subdomain setting subdomain = ""

from flask import Flask,url_for

app = Flask(__name__)
app.debug = True
'''
First in hosts Set domain name resolution(It's on this machine hosts Edit the corresponding domain name on the file ip Relationship between) 
Domain name resolution will resolve the local domain name first. If not, it will be resolved again dns The server
C:\Windows\System32\drivers\etc\hosts

127.0.0.1 mark.com
127.0.0.1 admin.mark.com

'''
app.config['SERVER_NAME'] = 'mark.com:5000' # This representative needs to access port 5000 when accessing this domain name

@app.route("/")
def index():

    return 'Domain name set successfully'

@app.route("/admin_demo/",subdomain='admin')
def admin_demo():

    return 'Setting subdomain name succeeded'

'''
Access the primary domain name in the browser
mark.com:5000/

Access subdomain name in browser
admin.mark.com:5000/admin_demo/

Note: the following path Path part normal write
'''

if __name__ == '__main__':
    app.run(host='127.0.0.1',port=5000) # The test server is unstable. Try to manually set the ip and port

00/admin_demo/

Note: the following path is written normally
'''

if name == 'main':
app.run(host ='127.0.0.1 ', port=5000) # test server is unstable. Try to manually specify ip and port

   [External chain picture transfer...(img-3bN7sxJ2-1631577287029)]

[External chain picture transfer...(img-WMWNlbMG-1631577287030)]
   
[External chain picture transfer...(img-g83GjcMi-1631577287030)]
   

Keywords: Python Flask

Added by smiley_kool on Fri, 19 Nov 2021 16:22:09 +0200