The aim of this tutorial is to guide you on how to create views and routes in Flask, a lightweight and powerful Python web framework.
By the end of this tutorial, you will:
Before starting, you should have:
In Flask, a route is a URL pattern that is used to find the appropriate view function for a particular URL. A route is defined using the @app.route()
decorator followed by a function that returns a response.
A view in Flask is a Python function that handles a client request and generates a response. This response can be a web page (HTML), a redirect, a 404 error, an XML document, an image, or any other type of response.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello, Flask!'
if __name__ == '__main__':
app.run(debug=True)
from flask import Flask
- This line imports the Flask module and creates a Flask web server from the Flask module.app = Flask(__name__)
- This line creates a new web application called "app".@app.route('/')
- This line is a decorator that tells Flask what URL should trigger the home
function. The '/'
URL corresponds to the main or home page.def home(): return 'Hello, Flask!'
- This is the view function named home
. It returns the string 'Hello, Flask!'
which is displayed in the user's browser when they navigate to the home page.if __name__ == '__main__': app.run(debug=True)
- This line ensures the server only runs if the script is executed directly from the Python interpreter and not used as an imported module.The expected output when you navigate to the home page (usually 'localhost:5000/' if running locally) is:
Hello, Flask!
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Welcome to the Home Page!'
@app.route('/about')
def about():
return 'Welcome to the About Page!'
if __name__ == '__main__':
app.run(debug=True)
@app.route('/about')
line defines a new route for the URL '/about'.def about(): return 'Welcome to the About Page!'
line defines a new view function that returns a different message.The expected output when you navigate to the 'about' page (usually 'localhost:5000/about' if running locally) is:
Welcome to the About Page!
In this tutorial, we have learned about routes and views in Flask. We have seen how to define routes using the @app.route()
decorator and how to create view functions that generate responses to client requests.
For further learning, you can explore how to:
You can find additional resources in the Flask Documentation.
Solution:
python
@app.route('/contact')
def contact():
return 'Welcome to the Contact Page!'
Solution:
python
@app.route('/user/<username>')
def user(username):
return 'Welcome, {}!'.format(username)
Remember, the key to mastering Flask (like any programming skill) is consistent practice. Happy coding!