Write a URL, reverse URL, page jump, and redirect today
URL-pass Parameter
Main app file code:
fromFlaskImportFlaskapp= Flask (__name__) @app. Route ('/')defHello_world ():return 'Hello world!'@app. Route ('/article/<id>')defarticle (ID):return 'The parameter you requested is:%s'%IDif __name__=='__main__': App.run ()
# # # URL Pass parameter:
1. The role of parameters: You can load different data in the same URL, but specify different parameters.
2. How to use parameters in flask:
‘‘‘
@app. Route ('/article/<id> ')
def article (ID):
Return ' The parameter you requested is:%s '%id
‘‘‘
* Parameters need to be placed in two angle brackets.
* Parameters in the view function that need to be placed in the same name as the parameters in the URL
Reverse URL
First, the forward refers to the contents of the view function by the parameters in the URL, then the inversion refers to the parameter content of the URL from the view function.
The code is as follows:
fromFlaskImportFlask,url_forapp= Flask (__name__) @app. Route ('/')defindex ():Print(Url_for ('my_list')) Print(Url_for ('article', id ='ABC')) return 'Hello world!'@app. Route ('/list/')defmy_list ():return 'List'@app. Route ('/article/<id>/')defarticle (ID):return 'the ID of your request is:%s'%IDif __name__=='__main__': App.run (Debug=true)
The output gets:
Note that here the article function, has the ID parameter, in the Url_for function needs to pass in the parameter, otherwise will error
# # # Reverse URL:
1. What is called Reverse URL: A conversion from a view function to a URL is called a reverse URL
2. Reverse the use of URLs:
* The URL reversal is used when the page is redirected
* In the template, url inversion is also used
Page jumps and redirects
The code is as follows:
fromFlaskImportFlask,redirect,url_forapp= Flask (__name__) @app. Route ('/')defindex (): Login_url= Url_for ('Login') returnRedirect (Login_url)return 'this is the homepage!'@app. Route ('/login/')deflogin ():return 'This is the login page!'@app. Route ('/question/<is_login>/')defquestion (is_login):ifIs_login = ='1': return 'This is the publish question and Answer page' Else: returnRedirect (Url_for ('Login'))if __name__=='__main__': App.run (Debug= True)
The functions implemented here are:
1. Go to the ' login ' login page by logging into the homepage
2. If the ' is_login ' parameter is not 1, it will jump to the login page
# # # page jumps and redirects
1. Use: When the user visits some need to log on the page, if the user is satisfied with the login, then you can let him redirect to the login page
2. Code implementation:
‘‘‘
From flask Import Redirect,url_for
Redirect (Url_for (' login '))
‘‘‘
Flask Web Development Road Three