Flask variable rules (build dynamic url)

Original Source:

http://codingdict.com/article/4867

 

  URL may be dynamically constructed by adding a portion of the variable parameters to the rule. The variable portion is labeled <variable-name>. It passed to the function associated with the rule as keyword arguments.

 

  In the following example, the parameter rule route () decorator contains additional to the URL '/ hello' of <name> variable part. Thus, if the http: // localhost: 5000 / hello / CodingDict as the URL in the browser, ** 'TutorialPoint' supplied to the hello () ** function as a parameter.

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)

 

  Save the above script is hello.py and run it from the Python shell. Next, open the browser and enter the URL http: // localhost: 5000 / hello / CodingDict.

 

  The following output will be displayed in the browser.

  Hello CodingDict!

 

  In addition to the default variable character string part, the following rules may also be configured using the converter -

No. Converter and notes
1 int accept integers
2 float for floating-point values
3 accepted as directory separators path slash

In the following code, we are using all of these constructors.

 1 from flask import Flask
 2 app = Flask(__name__)
 3 
 4 @app.route('/blog/<int:postID>')
 5 def show_blog(postID):
 6    return 'Blog Number %d' % postID
 7 
 8 @app.route('/rev/<float:revNo>')
 9 def revision(revNo):
10    return 'Revision Number %f' % revNo
11 
12 if __name__ == '__main__':
13    app.run()

 

  Run the code from the Python Shell. Access URL http in the browser: // localhost: 5000 / blog / 11.

  

  As given number show_blog () function parameters. The browser displays the following output -

  Blog Number 11

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

  This version () function occupies a float as an argument. The following results appear in the browser window -

  Revision Number 1.100000

 

  Flask Werkzeug URL rules-based routing module. This ensures that the URL form is unique and based on the precedent established by Apache.

Consider the following rules defined in the script -

 1 from flask import Flask
 2 app = Flask(__name__)
 3 
 4 @app.route('/flask')
 5 def hello_flask():
 6    return 'Hello Flask'
 7 
 8 @app.route('/python/')
 9 def hello_python():
10    return 'Hello Python'
11 
12 if __name__ == '__main__':
13    app.run()

 

  两条规则看起来都很相似,但在第二条规则中,使用了尾部斜线 (/) 。因此,它变成了一个规范的URL。因此,使用 / python 或 / python / 返回相同的输出。但是,在第一条规则的情况下, / flask / URL会导致 404 Not Found 页面。

Guess you like

Origin www.cnblogs.com/kaerxifa/p/11345032.html