Last Updated on 2021-06-29 by Clay
Route is the function we use to register the URML in Flask.
I recorded the following code in the previous experience note:
# -*- coding: utf-8 -*- from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return "Hello World!" if __name__ == '__main__': app.run()
Among them, “@app.route(‘/’)” is our registered website, and the website is directly the “root directory” of our written program-the symbol “/”.
What I want to record today is some configuration methods of this route, including registering different URLs, using variable input, invalid URLs, and automatically redirected URLs… etc.
Use Route to register different URLs
# -*- coding: utf-8 -*- from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'Index Page' @app.route('/test') def test(): return 'Test Page' if __name__ == '__main__': app.run(host='127.0.0.1', port=8000)
Output:
As you can see, I have registered two different URLs, and when I change them to the corresponding URLs on the browser, the corresponding text will be displayed.
This is a common usage of Route: register different URLs.
Enter parameters in the URL
When using Route to register a URL, we can set it to accept the parameters in the URL. I don’t think this explanation is easy to understand. It may be clearer by looking directly at the example.
# -*- coding: utf-8 -*- from flask import Flask from markupsafe import escape app = Flask(__name__) @app.route('/') def index(): return 'Index Page' @app.route('/<int:userID>') def hello(userID): return 'The user ID is: {}'.format(escape(userID)) if __name__ == '__main__': app.run(host='127.0.0.1', port=8000)
Output:
In this sample code, I entered a variable called userID and specified that only “int” can be entered as an integer. So we can clearly see that when I typed “123456”, the page returned “The user ID is: 123456” normally – but it was wrong when I typed “Clay”.
This is all because I limited the data type of the variables that can be entered.
The data types that can be entered are as follows:
string | Can accept strings, not “/” |
int | Accept positive integers |
float | Accept positive floating point numbers |
path | Can accept strings and “/” |
uuid | Can accept UUID |
Invalid, automatic redirect URL
The next record may be relatively useless information, just a simple common sense.
@app.route('/test01/') def test01(): return 'test01' @app.route('/test02') def test02(): return 'test02'
If the URLs we registered today are the two above, then in test01, the last “/” actually means there is no one, and the URL will be redirected to “/test” when input.
And test02 is a normal URL, but if we add “/” at the end of this URL today, an error will occur because the URL cannot be found.
References
- https://flask.palletsprojects.com/en/1.1.x/
- https://smalltowntechblog.wordpress.com/2017/07/13/flask-%E5%BE%9E%E5%9F%BA%E6%9C%AC%E7%9A%84%E8%B7%AF%E7%94%B1%E8%A8%AD%E5%AE%9A%E9%96%8B%E5%A7%8B/