Any site supports several types of addresses that users can access. For each address, a site uses a function that displays its content — a view function. For example, a list of movies is sorted by a particular tag. These pairs (a URL and a view function) make up a simple route. In this topic, we will discuss routes and ways to use them in your app.
Simple routes
As described above, the routes connect the application's URL paths to functions that contain the content for these paths. For example, when users access /about/, we may want to execute the render_about() function to show the particular content. Similarly, when they type in /products/, we would like to run render_products(). It is a method that returns different data.
To bind a URL with a view function, Flask uses decorators. Here's how we can create a route:
@app.route('/')
def hello_world():
return 'Hello World!'After starting the local server, we will see the following:
If you enter a path that is not registered in any router, the server will output the Not Found error.
Handling routes
In the simplest case, one URL corresponds to one function. Let's create two routes for our app: one for the main page and one for the information page at /about. We can do it by declaring view functions just like with the Hello world above:
@app.route('/')
def render_main():
return 'This is the main page'
@app.route('/about')
def render_about():
return 'Project Information'Yay, our mini-site has two pages already!
One of the important properties of a decorator is the ability to use multiple decorators for a single function. Suppose we have several pages that are under development. What we want to show is a message about it. We can do the following:
@app.route('/all')
@app.route('/about')
def construction_site():
return "Construction Site"In this case, we will display one HTML page for both /all/ and /about/.
Passing parameters
Sometimes we need to output dynamic content depending on the parameter that users requested in the address bar. For example, we need to show different profile pages for every employee. Creating thousands of routes like /employee/Ivan/, employee/Anna/, or employee/Alex/ is nothing but a headache. Don't worry; Flask has our back! It's time to learn how to do it like a pro. In the example with employees, we would need to designate the variable name variable in the route and pass it to the function as a parameter:
@app.route('/employee/<name>/')
def show_profile(name):
return "Employee Name: " + nameLet's see what happens. If you use 0.0.0.0:5000 and open the following link http://0.0.0.0:5000/employee/Ivan/:
In the example above, the value inside the <> brackets indicates a variable that allows us to declare route rules. In this case, the rule is that the show_profile function will handle every request matching the /employee/<name>/ template.
Passing several parameters
Sometimes we need to accept several parameters from the address bar for a single route. For example, we have a site on movies. It stores two characteristics — a title and genre: movies.com/movies/horror/saw/
To pass them, use the following pattern:
@app.route('/movies/<genre>/<title>/')
def render_movie(genre, title):
return "There will be a " + genre+ " movie " + title + "here"Let's get it going. When you start the app and go to http://127.0.0.1:5000/movies/horror/saw/, you'll get a page with the specified message:
Of course, these are the simplest cases. In real life, you'll be probably processing these values and using them for filtering.
Type conversion
A URL is a string, so the data obtained from it is passed to the function in the form of a string. You can see it yourself by using type(). Create a route and go to /movies/1/:
@app.route('/movies/<movies_id>/')
def render_movies(movies_id):
print(type(movies_id))
return ""You will see <class 'str'> in the console.
However, we don't always need a string. Flask allows us to change the immediate type of a variable:
@app.route('/movies/<int:movies_id>/')
@app.route('/movies/<float:movies_id>/')
Try changing the code the following way:
@app.route('/movies/<int:movies_id>/')
def render_book(movies_id):
print(type(movies_id))
return ""You will see <class 'int'> in the console.
Flask accepts a few other variable types. If you feel curious, refer to the Official Documentation.
Conclusion
We have discussed the basics of routes; we know how to take one or more parameters in the address bar and change their type. Here are quick notes:
Routes bind a URL to a view function;
A view function responds to the request and returns some data;
An
@app.routedecorator binds a URL and a function in Flask;Routes can be generated dynamically by accepting variables.
It's time to put what we've learned into practice!