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/
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)
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})
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 methods
parameters 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
- 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
user_bp=Blueprint('user',__name__)
- Operate on this blueprint object, register routes, specify static folders, and register template filters
@user_bp.route('/')
def user_profile():
return 'user_profile'
- Register the blueprint object on the application object
app.register_blueprint(user_bp)
url_prefix is used to add a prefix when this route is matched
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__.py
file of the Python package
--------- project # 工程目录
|------ main.py # 启动文件
|------ user #用户蓝图
| |--- __init__.py # 此处创建蓝图对象
| |--- passport.py
| |--- profile.py
| |--- ...
|
|------ goods # 商品蓝图
| |--- __init__.py
| |--- ...
|...
Register the blueprint.
Pay attention to add the following sentence, load the content of views.
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_prefix
parameters 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_admin
directory.
You can also static_url_path
change 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
-
This access in Django will get all routing information
-
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 -
How to solve cross-domain access? Django-cors provides a request for processing options. In the middleware, the options request
options do not involve business logic. It only asks for interface information. The source of the request to be allowed
only needs to use the cors solution for processing. The ideas are the same -
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.
-
Pay attention to the three steps of the blueprint: 1. Create the blueprint 2. Register the blueprint route 3. Register the blueprint
-
10. According to pep8, guide the package, and put the guide module up as much as possible -
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
run in debug mode. Debug mode, server error will not display detailed error information