The routing and blueprint of the flask framework

routing

@app.route("/itcast")
def view_func():
    return "hello world"

1 Query routing information

  • Command line
flask routes
Endpoint  Methods  Rule
--------  -------  -----------------------
index     GET      /
static    GET      /static/

Insert picture description here
Flask will provide routing to access static files by default

  • Get in the program

The routing mapping information of the entire Flask application is stored in the url_map attribute in the application, and routing information can be obtained by reading this attribute

print(app.url_map)

Insert picture description here

If you want to traverse the routing information in the program, you can use the following method

for rule in app.url_map.iter_rules():
    print('name={} path={}'.format(rule.endpoint, rule.rule))

demand

Return all routing information in the application in json format through access/address

achieve

@app.route('/')
def route_map():
    """
    主视图,返回所有视图网址
    """
    rules_iterator = app.url_map.iter_rules()
    return json.dumps({
    
    rule.endpoint: rule.rule for rule in rules_iterator})

Insert picture description here

2 Specify the request method

In Flask, the default request method for routing is defined as:

  • GET
  • OPTIONS (included) -> simplified Get request, the user asks the server interface information
  • HEAD (included) -> simplified Get request, only the response header processed by the get request is returned, not the response body

For the same request, using get will return all the information, using head, only contains the status code and response headers

Use methodsparameters to specify the request method of an interface by yourself

The methods attribute will modify the request method of the route in an overriding manner. The first route below will only support post, and the second route will only support get and post.

@app.route("/itcast1", methods=["POST"])
def view_func_1():
    return "hello world 1"

@app.route("/itcast2", methods=["GET", "POST"])
def view_func_2():
    return "hello world 2"

blueprint

demand

In a Flask application project, if there are too many business views, can the business units divided in a certain way be maintained separately, and the views, static files, and template files used by each unit can be separated independently?

For example, from a business perspective, the entire application can be divided into user module units, commodity module units, and order module units. How to develop these different units separately and finally integrate them into a project application?

How is this requirement achieved in Django?

blueprint

Django is called a blueprint, and flask is called a sub-application. The
blueprint should include the resources used by this sub-application as much as possible.
In Flask, the blueprint is used to organize and manage the modules.

A blueprint can actually be understood as a container object that stores a set of view methods. It has the following characteristics:

  • An application can have multiple Blueprints
  • You can register a Blueprint to any unused URL such as "/user", "/goods"
  • Blueprint can have its own templates, static files, or other general operation methods alone, it is not necessary to implement the views and functions of the application
  • When an application is initialized, it should register the Blueprint
    ** but a Blueprint is not a complete application, it cannot run independently of the application, but must be registered in a certain application. **Like Django, it cannot be run independently, it needs to be registered in a certain project

How to use

Using blueprints can be divided into three steps

  1. To create a blueprint object, the
    first parameter is the name of the blueprint and
    __name__ is used to determine the location of the blueprint
    Insert picture description here
 user_bp=Blueprint('user',__name__)
  1. Operate on this blueprint object, register routes, specify static folders, and register template filters
 @user_bp.route('/')
 def user_profile():
     return 'user_profile'
  1. Register the blueprint object on the application object
 app.register_blueprint(user_bp)

Insert picture description here
Insert picture description here
url_prefix is ​​used to add a prefix when this route is matched
Insert picture description here

Single file blueprint

You can create blueprint objects and define views into one file.

Catalog (package) blueprint

Views can be placed in a single file or in multiple files

For a blueprint that intends to contain multiple files, usually the creation of the blueprint object is placed in the __init__.pyfile of the Python package

--------- project # 工程目录
  |------ main.py # 启动文件
  |------ user  #用户蓝图
  |  |--- __init__.py  # 此处创建蓝图对象
  |  |--- passport.py  
  |  |--- profile.py
  |  |--- ...
  |
  |------ goods # 商品蓝图
  |  |--- __init__.py
  |  |--- ...
  |...

Insert picture description here
Insert picture description here
Register the blueprint.
Insert picture description here
Pay attention to add the following sentence, load the content of views.
Insert picture description here
This sentence must be put at the end, otherwise it will cause circular references.

Extended usage

1 Specify the URL prefix of the blueprint

Use url_prefixparameters to specify when registering blueprints in the app

app.register_blueprint(user_bp, url_prefix='/user')
app.register_blueprint(goods_bp, url_prefix='/goods')

2 Static files inside the blueprint

Unlike the application object, the route of the static directory is not registered by default when the blueprint object is created. We need to specify the static_folder parameter when creating it .

The following example sets the static_admin directory in the directory where the blueprint is located as a static directory

admin = Blueprint("admin",__name__,static_folder='static_admin')
app.register_blueprint(admin,url_prefix='/admin')

Now you can use the static files in the /admin/static_admin/<filename>access static_admindirectory.

You can also static_url_pathchange the access path

admin = Blueprint("admin",__name__,static_folder='static_admin',static_url_path='/lib')
app.register_blueprint(admin,url_prefix='/admin')

3 Blueprint internal template catalog

The default template directory of the blueprint object is the system template directory. You can use the template_folder keyword parameter to set the template directory when creating the blueprint object

admin = Blueprint('admin',__name__,template_folder='my_templates')

notes

  1. This access in Django will get all routing information
    Insert picture description here

  2. for i in
    iterable object The position of the iterable object is obtained by calculation. It is good to know what object to traverse in your mind

  3. How to solve cross-domain access? Django-cors provides a request for processing options. In the middleware, the options request
    Insert picture description here
    options do not involve business logic. It only asks for interface information. The source of the request to be allowed
    Insert picture description here
    Insert picture description here
    only needs to use the cors solution for processing. The ideas are the same

  4. The purpose of creating apps in Django is to reuse. In this way, each app can be separated from Django. For example, the user module can be directly used by other websites, and the app can be reused and extended.

  5. Pay attention to the three steps of the blueprint: 1. Create the blueprint 2. Register the blueprint route 3. Register the blueprint

  6. Insert picture description here

  7. Insert picture description here

  8. Insert picture description here

  9. Insert picture description here
    10. According to pep8, guide the package, and put the guide module up as much as possible

  10. DEBUG in Django supports static files. Errors in the backend will be displayed directly on the front-end page. After modifying the code, the development server will be restarted automatically. Flask's debug does not support static files, but supports the latter two to
    Insert picture description here
    run in debug mode. Debug mode, server error will not display detailed error information

Guess you like

Origin blog.csdn.net/weixin_43297727/article/details/115249142