Flash framework - detailed url

1 what is a url?

URL is a unified resource locator (short for Uniform Resource Locator), a concise representation of the location and access method of resources available from the Internet, and the address of standard resources on the Internet. Every file on the Internet has a unique URL, which contains information indicating the location of the file and what the browser should do with it.

A URL consists of the following parts:

  • scheme: represents the access protocol, generally http or https and ftp.
  • Host: host name, domain name, such as www.baidu.com.
  • Port: port number. When you visit a website, the browser uses port 80 by default.
  • Path: path. For example: www.baidu.com/Public/linux/?python=aladdin#23, the public / Linux behind www.baidu.com is path.
  • Query string: query string, for example: www.baidu.com/s?wd=python,? The following python=aladdin is the query string.
  • Anchor: the anchor point is generally not used in the background, and the front end is used for page positioning. For example: https://www.oldboyedu.com/Public/linux/?fr=aladdin#23 The # next 23 is the anchor

2 why is there a url?

As the name suggests, the uniform resource locator is used for positioning. Our web development is nothing more than calling the program, and the specific program we call is called Python view function. The URL establishes a one-to-one mapping relationship with Python view function, which is easy to understand and can be understood as a command that triggers a Python function or class.

3 how to apply url?

3.1 the difference between URL and route.

What we need to call the interface is a specific code, that is, a python class or Python function, and the url is the specific mapping of this code, that is, we can find a specific Python class or Python function through the url, which is the url. Routing is a program that locates a specific Python class or Python function according to the url. This program is called routing.

Using a route in a flask program is called registration route. It uses the app.route () decorator provided by the program instance to register a route, and the string in parentheses is the url. The process of registering a route is to complete the mapping between the url and the python class or function. It can be understood that a table will save the corresponding relationship between the url and the python class or function. In this way, we can find the corresponding program by accessing flash with url.

def hello_world():
    return 'Hello World!'

According to this relationship, we write another route

def student_list():
    return 'students'

3.2 two types of URL parameters

3.2.1 dynamic routing parameters

If you carefully observe some URL formats of daily services, you will find that many addresses contain variable parts. For example, you want to find a specific student according to the student's id, <student_ ID > / is still in the path section, but you don't need to write multiple routes. We support this variable route in flash.
See code:

def student_list(student_id):
    return 'student{}Information of number'.format(student_id)

Keyword: there is a variable part in the path to achieve the effect of parameter transmission. We call it dynamic routing parameter transmission dynamic route filtering

You can limit the data type of parameters, such as the above article details and student_id must be of integer type

def article_detail(student_id):
    return 'student{}Information of number'.format(student_id)

There are several types of filtering:
String: the default data type, receiving a string without any slash '\ /'
int: integer
float: floating point
path: similar to string, but accepts slashes. For example, you can accept the parameter / aa/bb/cc / and put multiple together
uuid: only strings in uuid format are accepted,
​ ✔ Tip: uuid is the only string in the universe

The above constraints are in the following format. The int in the example can be replaced by string, float, path and UUID:

def article_detail(student_id):
    return 'student{}Information of number'.format(student_id)

any: multiple paths can be specified, such as the following example
url_ The variable name of path is self-defined

def item(url_path, id):
    if url_path == 'student':
        return 'student{}details'.format(id)
        return 'class{}details'.format(id)

What are the applicable scenarios for dynamic routing?
If you want to increase the exposure of the website, you can consider using dynamic routing, because you take path as a parameter, and the search engine algorithm will define you as a static page, which will not change often, which is conducive to the optimization of the search engine. However, if it is an internal management system of the company, it is not necessary to use dynamic routing, because the internal system has no requirements for exposure.
key word:

  • The above parameters we accept are in the form of path. This form of parameter transmission is called dynamic route parameter transmission, which is conducive to the optimization of search engine.

3.2.2 query string parameter transfer

What is a query string described above:
If we enter the parameters of www.baidu.com/s? WD = Python & ad = flask in the browser, this? The key=value after is the query string,
You can write multiple key = values and connect them with &. We use the query string as a parameter to request our flash program, which is the query string parameter.
When registering the route, we will set parameters in the path part and the formal parameters of the function to accept the path parameters. When transmitting parameters to the query string, we need to import the request object from the flash module, and use the request.args attribute to get the value of the query string in our program according to the key of the query string.
args is an attribute of request. Its essence is an immutableMultiDict object of Werkzeug dependent package, which is used to parse the query string we passed in. immutableMultiDict object also inherits the Dict class, so it can be obtained by using the. get() method of the dictionary. Of course, if we need to obtain the native unresolved native query string, we can use query_string attribute.

from flask import Flask,request
def school_name_list():
    name = request.args.get('name')
    age = request.args.get('age')
    return "The student's name is{},Age is{}".format(name, age)

3.3 url_ Use of for():

3.3.1 introduction view function:

When we visit a web site and call the flash project, we need to call a specific code, that is, a python class or Python function. Here, the python class is called the view class and the python function is called the view function.

3.3.2 url_ Function of for():

If we want to use a URL in the view function, such as returning to the front end, or we return a template file in the view function, we will use the URL. The URL is equivalent to a key to open some resources. If you modify the URL rule written by the registered route, it is equivalent to modifying the key. If other view functions still use the original key, it will be invalid. If the project is a large project, it is unreasonable for you to manually change the involved URL. url_for() is used to solve this problem.

3.3.3url_ Principle of for():

Using the feature that the name of the view function generally does not change, use the name of the view function to dynamically and accurately obtain the url for development and use.

url_for('View function name')   # Output the url of the view function

Specific examples:

from flask import Flask,url_for

app = Flask(__name__)

def demo1():
    print(url_for("book"))  # Note that this refers to the name string format of the view function

    return url_for("book")

def book():

    return 'flask_book'

if __name__ ==  "__main__":

We visit directly , the routed distribution will trigger the execution of demo1. As shown in the figure

3.3.4 url_ How does for handle dynamic view functions?

If you want to obtain a dynamic route, you must assign a value to the dynamic path part in the form of keyword arguments. Note that the dynamic path part must be assigned,

def demo2():
    student_url = url_for('student', id=5, name='mark') # id It's dynamic path of key Must be assigned,															# name will be passed in as a query string

    return student_url

def student(id):
    return 'student {}'.format(id)

Console output:

Browser output:

3.3.5 url_ How does for add a query string to a URL?

If you want to spell out the query string after the path, put it in the URL in the form of keyword arguments_ As a parameter in for (), it will be automatically spelled into a path

def demo3():
    school_url = url_for('school', school_level='high', name='college') 
    # The query parameters to be spliced are written in the URL in the form of keyword arguments_ For Li

    return school_url

def school():

    return 'school message'

Console output:

Browser output:

3.4 custom dynamic routing filter

3.4.1 regular matching of custom dynamic routing filters

We can define a dynamic routing filter rule by inheriting the BaseConverter class of werkzeug.routing

from flask import Flask,request
from werkzeug.routing import BaseConverter

app = Flask(__name__)
app.debug =True

class TelephoneConverter(BaseConverter):
    regex = '1[3857]\d{9}' #Lower right slash d

app.url_map.converters['tel'] = TelephoneConverter

def student_detail(telenum):

    return 'What is the student's mobile phone number{}'.format(telenum)

if __name__ == '__main__':

be careful:

  1. Customize the dynamic routing filter class, which must inherit the BaseConverter class of werkzeug.routing

  2. Specify the routing rule through the regex attribute

  3. Map the custom class to app.url_map.converters (which is essentially a dictionary)
    app.url_map.converters['tel'] = TelephoneConverter

Effect achieved:

3.4.2 processing dynamic routing with custom dynamic routing filter

Customize a class that can not only realize regular matching by inheriting the BaseConverter class of werkzeug.routing. Let's introduce the following two methods:

  • Implement to in this class_ Python method:
    The return value of this method will be passed to the formal parameters of the view function. We can use this method to deal with the dynamic routing part of the url.

  • Implement to in this class_ URL method:
    When you flip the url, you use the url_ When using the for function, we pass in the specified dynamic routing part and trigger to_url method. The return value of this method will be spliced on the non dynamic route to generate a url format that meets the requirements.

from flask import Flask,request,url_for
from werkzeug.routing import BaseConverter

app = Flask(__name__)
app.debug =True

class ListConverter(BaseConverter):
    regex = '.*'     # This regex represents the meaning of matching. You can make url rules according to your own needs
    def to_python(self, value):
        '''This function is used to get the dynamic parameters in the route and assign them to value,
          Can be in to_python Operating dynamic parameters,
          Returns the result of the operation to the formal parameters of the view function'''
        return value.split('+')

    def to_url(self, value):
        '''This function is used for and url_for Used together,
           url_for By assigning to dynamic parameters(In the form of keyword arguments)Assign to value
           We can operate according to our needs url_for The parameters passed in,
           Then an ideal dynamic routing content splicing is returned url upper'''
        return '+'.join(value)

app.url_map.converters['list'] = ListConverter

def student_list(students):
    print(url_for('student_list',students=['a','b'])) # Output / student_list/a+b/

    return '{}'.format(students)

if __name__ == '__main__':

Prove to_ The python () method processes the dynamic routing part during access into a list.

Prove our to_ The URL () method takes the URL_ The dynamic routing part passed in by the for() function is converted from a list to a concatenated string.

Output / student_list/a+b/

return '{}'.format(students)

if name == 'main':

prove`to_python()`Method processes the dynamic routing part of the access time into a list.
 [External chain picture transfer...(img-2h9EymMm-1631486835835)]
Prove our `to_url()` Method`url_for()`The dynamic routing part passed in by the function is converted from a list to a splicing string.
  [External chain picture transfer...(img-wPSVLuHx-1631486835835)]

Tags: Python Flask

Posted on Fri, 19 Nov 2021 15:09:57 -0500 by robviperx