Flask variable rules

By adding a variable part to the rule parameter, the URL can be constructed dynamically. This variable is partly marked as. It is passed as a keyword argument to the function associated with the rule.

In the following example, the rule parameter of the route() decorator contains the one appended to the URL'/hello'. Therefore, if you enter http://localhost:5000/hello/w3cschool as the URL in the browser,'w3cschool' will be provided as a parameter to the hello() function.

from flask import Flask
app = Flask(__name__)

@app.route('/hello/<name>')
def hello_name(name):
   return 'Hello %s!' % name

if __name__ == '__main__':
   app.run(debug = True)

Open a browser and enter the URL http://localhost:5000/hello/w3cschool.

The following output will be displayed in the browser: Hello w3cschool!

In addition to the default string variable part, you can also use the following converter to build rules:
Insert picture description here
In the following code, all these constructors are used:

from flask import Flask
app = Flask(__name__)

@app.route('/blog/<int:postID>')
def show_blog(postID):
   return 'Blog Number %d' % postID

@app.route('/rev/<float:revNo>')
def revision(revNo):
   return 'Revision Number %f' % revNo

if __name__ == '__main__':
   app.run()

Visit the URL http://localhost:5000/blog/11 in the browser.

The browser displays the following output: Blog Number 11

Enter this URL in the browser-http://localhost:5000/rev/1.1

The revision() function takes a floating point number as a parameter. The following result is displayed in the browser window: Revision Number 1.100000

Flask's URL rules are based on Werkzeug's routing module. This ensures that the URL formed is unique and based on the precedent set by Apache.

Consider the rules defined in the following script:

from flask import Flask
app = Flask(__name__)

@app.route('/flask')
def hello_flask():
   return 'Hello Flask'

@app.route('/python/')
def hello_python():
   return 'Hello Python'

if __name__ == '__main__':
   app.run()

These two rules look similar, but in the second rule, a slash (/) is used. Therefore, it becomes a canonical URL. Therefore, using /python or /python/ returns the same output. However, if it is the first rule, the /flask/ URL will generate a "404 Not Found" page.

Guess you like

Origin blog.csdn.net/baidu_24752135/article/details/114453268