Python's Flask routing and blueprint

1. Routing

@app.route('/index')
def index():
    return "hello world"

1.1 query routing information

  • Command line mode

Note: at least flag must be specified_ App environment variables

>flask routes
Endpoint  Methods  Rule
--------  -------  -----------------------
index     GET      /index
static    GET      /static/<path:filename>

  • Get in program
print(app.url_map)
#Map([<Rule '/index' (HEAD, GET, OPTIONS) -> index>,<Rule '/static/<filename>' (HEAD, GET, OPTIONS) ->static>])

If you want to use variable routing information in the program, you can use the following methods

for rule in app.url_map.iter_rules():
    print('name={%s} path={%s}' %(rule.endpoint, rule.rule))
    
#name={index} path={/index}
#name={static} path={/static/<path:filename>}

Test:
Return all routing information in the application in json mode through access / address

@app.route('/')
def route_map():
    rules_iter = app.url_map.iter_rules()
    return json.dumps({rule.endpoint:rule.rule for rule in rules_iter})

1.2 specify request method
In Flask, define a route. The default request method is:

  • GET
  • OPTIONS (included)
  • HEAD (self-contained)

You can specify the request mode of an interface by using the methods parameter

@app.route('/index', methods=['GET'])
def index():
    return "hello world"

@app.route('/', methods=['GET','POST'])
def route_map():
    rules_iter = app.url_map.iter_rules()
    return json.dumps({rule.endpoint:rule.rule for rule in rules_iter})

2. Blueprint

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

For example, from a business perspective, the whole application can be divided into user module unit, commodity module unit and order module unit. How can these different units be developed separately and finally integrated into a project application?

2.1 blueprint
In Flask, Blueprint is used to organize and manage modules

The blueprint can actually be understood as a container object that stores a set of view methods, which has the following characteristics:

  • An application can have multiple blueprints
  • A Blueprint can be registered under any unused URL, such as "/ users" and "/ goods"
  • Blueprint can have its own template, static file or other general operation methods. It does not have to implement the views and functions of the application
  • When an application is initialized, it should register the Blueprint to be used

A Blueprint is not a complete application. It cannot run independently of the application, but must be registered in an application.

2.2 mode of use

There are three steps to using Blueprint

  1. To create a blueprint object, you can create a new package, such as users, and then_ init_. Create blueprint in PY
# Create blueprint
users_bp = Blueprint('users', __name__, static_folder='static_users')
# When importing views, note that the order must be placed behind the blueprint
from .views import *
  1. Operate on this blueprint object, register routes, specify static folders, register template filters, etc. For example, create a views.py file under the users package
from users import users_bp

@users_bp.route('/')
def user_info():
    return "User information"
  1. Register the blueprint on the flash application object in the entry file
from flask import Flask

from users import users_bp

app = Flask(__name__)

# Register blueprint url_prefix specifies the url prefix
app.register_blueprint(users_bp, url_prefix='/users')

Single document blueprint
You can create blueprint objects and define views in one file.

Directory (package) blueprint
For a blueprint that is intended to contain multiple files, the blueprint creation object is usually placed in the Python package__ init__.py file. This is the case demonstrated above

2.3 extended usage

1) Specifies the url prefix for the blueprint
Use URL when registering blueprint in application_ The prefix parameter specifies

app.register_blueprint(users_bp, url_prefix='/users')

2) Blueprint internal static file

Unlike the application object, the route of the static directory will not be registered by default when the blueprint object is created. We need to specify static when creating_ Folder parameter.

The following example sets the static/users directory under the project directory as a static directory

# Create blueprint
users_bp = Blueprint('users', __name__, static_folder='static_users')
# http://localhost:5000/users/static_users/1.png

You can now use / users/static_users / access static_ The static files in the users directory.

You can also use static_url_path change access path

users_bp = Blueprint('users', __name__, static_folder='static_users', static_url_path='/static')
# http://localhost:5000/users/static/1.png

3) Blueprint internal template directory
The default template directory of blueprint objects is the template directory of the system. You can use template when creating blueprint objects_ Folder keyword parameter setting template directory

users_bp = Blueprint('users', __name__,template_folder='templates_users', static_folder='static_users', static_url_path='/static')

Keywords: Python RabbitMQ batch

Added by auamy on Tue, 30 Nov 2021 12:11:48 +0200