Skip to content

[Python] Flask Study Notes (1): Introduction of Route

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:

stringCan accept strings, not “/”
intAccept positive integers
floatAccept positive floating point numbers
pathCan accept strings and “/”
uuidCan 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


Read More

Leave a Reply