Home > Courses > Flask: Python Web Development > Routes and Views

Routes and Views

Subject: Flask: Python Web Development
Modern web applications use meaningful URLs to help users. Users are more likely to like a page and come back if the page uses a meaningful URL they can remember and use to directly visit a page.

Routes is the association between the URL or web address and the function that it. In the previous topic, we created a route using the @app.route("/") decorator and bind it to an index function as follows:


@app.route("/") 
def index(): 


Functions with decorators are commonly referred to as views in Flask.

In our example, the index() view lead us the
root URL or the homepage of our web application.

If the web app is deployed on a live server with the domain name www.ex‐
ample.com
then browsing http://www.example.com on your browser would trigger the index() view to run on the server.

But because our web app is on a local development server as we have in previous topic we accessed it as follows:

http://localhost:5000/

The return value of this function (also known as
response) is what the site visitor would see on the browser in this case "Hello, TEA Learn".


@app.route("/") 
def index(): 
     return ("Hello, TEA Learn")
<br />


More views
If we are to have more views, then we will need to access them through their respective URL path:

Example 1

<br />from flask import Flask
<br />app = Flask(__name__) 
<br />
@app.route("/") 
def index(): 
       return "Welcome to TEA Learn!"
<br />
<br />@app.route("/about") 
<br />def about(): 
<br />       return "<h3>About Us</h3> TEA Learn"
<br />
<br />@app.route("/contact_us") 
<br />def contact(): 
<br />       return "<h3>Contact Us</h3> benjamin.onuorah@gmail.com"
<br />
<br />if __name__ == '__main__': 
<br />       app.run(debug=True)
<br />


In this example 1, we have created three views index, about and contact. These views can be access as follow after running the program, browse the following URL

index view
http://localhost:5000/

about view
http://localhost:5000/about

contact view
http://localhost:5000/contact_us

each one will trigger its function and the client will get each response displayed on the web browser.

Dynamic route
Dynamic route allows the possibility of appending a value to the URL which in turn is added as input or argument to the route function to load a dynamic content.

Example 2

from flask import Flask
app = Flask(__name__) 

@app.route("/team/<name>")
def team(name):
       return "About "+ name

if __name__ == '__main__': 
       app.run(debug=True)

When accessing such route, it expect the name to be added to the end of the URL for example:
http://127.0.0.1:5000/team/Emeka

And as such the value if feed to the function to load a dynamic content, you can try more names e.g ..../team/Ben


By: Benjamin Onuorah

Comments

No Comment yet!

Login to comment or ask question on this topic


Previous Topic Next Topic

Supported by