当前位置:网站首页>Flask (III) -- variable rules

Flask (III) -- variable rules

2022-06-11 09:27:00 zju_ cbw

You can dynamically build by adding variable parts to rule parameters URL. This variable part is marked as <variable-name>. It is passed as a keyword parameter to the function associated with the rule .


In the following example ,route() The decorator's rule parameter contains the rules attached to URL /hello Of <name> Variable part . therefore , If you type URL: http://localhost:5000/hello/nhooo, that nhooo Will be provided as a parameter to 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)

Run the top Python Script , Then open the browser and type URL http://localhost:5000/hello/nhooo. See in the browser Hello nhooo!

In addition to the default string variable section , You can also use the following converter to construct rules

converter describe
int Accept integers
float For floating point values
path Accept slash as directory separator (/)

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()

Run the above code , Access in a browser URL http:// localhost:5000/blog/11. You can see it in the browser Blog Number 11

Enter... In the browser URL http://localhost:5000/rev/1.1. You can see it in the browser Revision Number 1.100000

Flask Of URL Rule based Werkzeug The routing module of . This ensures the formation of URL Is the only one. , And based on Apache Established precedent .

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()

Both rules look very similar , But in the second rule , Use a trailing slash (/). therefore , It became a standard URL. therefore , Use /python or /python/ Return the same output . however , In the case of the first rule , URL: /flask/ It can lead to 404 Not Found page .

原网站

版权声明
本文为[zju_ cbw]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203012301369720.html