brief introduction
The main knowledge points involved in this chapter are:
- Routing function app Route and add_ url_ Use of rule function
- Basic use of standard view functions
- Basic application of view class based on method
- The basic application of decorators and the method of using decorators on behalf of parameters
- Role definition and application of blueprint
app.route and add_url_rule introduction
In flash applications, routing refers to the mapping between the user request url and the view function. The relationship between URLs is called mapping, and the program that deals with the relationship between URLs and functions becomes routing. Flash framework finds the corresponding view function according to the predefined url rules that the url of http request matches in the routing table, and returns the execution result of the view function to the server.
app.route usage
In the flash framework, @ app. Is used by default Route decorator
@app.route("/") def hello world(): return 'hello world
Use app The route decorator will save the relationship between the URL and the view function executed to the app url_ Map attribute implements the binding between URL and "/" and view function.
We can also use url_for('hello_world ') reverses to get url' '
@app.route('/',endpoint='index') def hello_world(): return 'hello world'
Once we use the endpoint parameter, we use the url_ When for() is reversed, the view function name cannot be used, but the custom function url name has been used
url_for('index')
add_ url_ Use of rules
We can also use add_url_rule to bind the view function and URL.
add_url_rule(self,rule,endpoint=None,view_func=None,provide_automatic_options=None,**options)
* rule:set up url value * endpoint: to url Set name * view_func:Specifies the name of the view function
The endpoint in the above code only specifies the url name in view_func specifies the name of the view function
Flash class view
The views we contacted before are all functions, which are generally referred to as view functions. The views of flash class can generally be divided into standard class views and class views of drop based methods.
Features of standard class view:
- Must inherit flash views. view
- Dispatch must be implemented_ The request method must also return a response, or a subclass object, or a string or tuple
- Must pass app add_ url_ Rule (rule, endpoint, view_func) is used to map URL and view_ Func parameter requires as_view class method conversion
- If endpoint is specified, the URL is used_ For inversion must use the value specified by endpoint. If not specified, you can use as_ The view function name is specified in the view (view name) as the inversion
app.py
from flask import Flask,render_template app=Flask(__name__)#Flash function initialization class Ads(views.View):#Define view class Ads def __init__(self):#instantiation super().__init__()#Inherited from__ init__ method self.context={ #set up 'ads':'This is a couplet advertisement' } #Defining the index class inherits from Ads and rendering template class Index(Ads): def dispatch_request(self): return render_template('index.html',**self.context) class Login(Ads): def dispatch_request(self): return render_template('login.html',**self.context) class Register(Ads): def dispatch_request(self): return render_template('register.html',**self.context) #Add route app.add_url_rule(rule='/',endpoint='index',view_func=Index.as_view('Index')) app.add_url_rule(rule='/login/',endpoint='login',view_func=Index.as_view('login')) app.add_url_rule(rule='/register/',endpoint='register',view_func=Index.as_view('register')) #function if __name__=='__main__': app.run(debug=Ture)
Note:__ init__ The first parameter of the method is always self, which represents the instance itself
Method class based view
Flash provides another kind of view views. Methonview, execute different functions for each http method (mapped to the lower case method with the same name of the corresponding method)
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> .div1 { height: 180px; width: 380px; border: 1px solid #8A8989; margin: 0 auto; } .input { display: block; width: 350px; height: 40px; margin: 10px auto; } .button{ background: #2066c5; color: white; font-size: 18px; font-weight: bold; height: 50px; border-radius: 4px; } </style> </head> <body> <div class="div1">< action="login" method="post"><form> <input type="text" class="input" name="username" placeholder="enter one user name"> <input type="text" class="input" name="password" placeholder="password"> <input type="submit" value="Sign in" class="input button"> </form>></div> </body> </html>
Flash decorator
The essence of decorator is a python function, which allows other functions to add additional functions without any code changes. The return value of decorator is a human function object.
from flask import Flask#Import flash module app=Flask(__name__)#Flash framework initialization @app.route('/')#Define router def hello_world():#Define view functions return "hello world"#Return value def user_login(func):#Define a function so that func() receives as a parameter def inner():#Define the inner() function print('Login operation') func()#Execute func function return inner def news():#Define function news() print('This is the details page of the news') show_news=user_login(news)#Pass new as a parameter to user_login() function shows_news()#implement print(show_news.__name__) if __name__ =='__main__': app.run()
Using decorators for functions with arguments
1. Variable parameters of function
def func():
*: represents tuple with unlimited length
**: represents a key value pair
*args: represents tuple with unlimited length
**kwargs: represents key value pairs, and the number is unlimited
2. Use decorator for parameters
from flask import Flask#Import flash module app=Flask(__name__)#Flash framework initialization @app.route('/')#Define router def hello_world():#Define view functions return "hello world"#Return value def user_login(func):#Define a function so that func() receives as a parameter def inner(*args,**kwargs):#Define the inner() function print('Login operation') func(*args,**kwargs)#Execute func function return inner @user_login def news(): print(news.__name__) print('This is the details page') news(); @user_login def news_list(*args): page=args[0] print('This is the third on the news list'+str(page)+'page') news_list(5) if __name__ =='__main__': app.run()
blueprint
Definition of blueprint: the collection of operations to be performed after the blueprint is registered in the application. When allocating the request, flash associates the blueprint with the view function and generates the url before the two ends.
Blueprints can greatly simplify large-scale applications and provide centralized registration entry for expansion.
The purpose of the blueprint is to realize the view function of each module, unload different py files, import shunts in the main view, have view modules, and register blueprint objects.
Note: the name of view function and blueprint cannot be the same
from flask import Flask#Import flash module app=Flask(__name__)#Flash framework initialization @app.route('/')#Define router def hello_world():#Define view functions return "hello world"#Return value app.register_blueprint(new.new_list)#The blueprint object new in the news module_ List register to app app.register_blueprint(product.product_list)#Transfer the blueprint in the product module to product_list register to app if __name__=='__main__': app.run(debug=True)
news.py
from flask import Blueprint #Import module new_list=Blueprint('news,__name__')#Create a Blueprint object. The first parameter can be regarded as the name of the Blueprint object #In an app, the name cannot be repeated with other Blueprint names #In the second parameter__ name__ Used as initialization @new_list.route("/news")#Use blueprint objects as app s def new():#Define function news() return "This is the of the news module"
product.py
from flask import Blueprint #Import module new_list=Blueprint('product,__name__')#Create a Blueprint object. The first parameter can be regarded as the name of the Blueprint object #In an app, the name cannot be repeated with other Blueprint names #In the second parameter__ name__ Used as initialization @new_list.route("/product")#Use blueprint objects as app s def product():#Define function product() return "This is the product module"