Creating routes in Flask
In this tutorial, you will learn about creating routes in Flask, a popular micro web framework written in Python. Routing in Flask is the mechanism that associates URLs with Python functions, allowing the application to respond to different HTTP requests on different URLs.
Introduction to Routing
When developing a web application, one of the most common tasks you'll need to accomplish is defining various routes or URLs that the application will respond to. In Flask, routes are created using the @app.route()
decorator to bind a function to a URL.
Getting Started
Firstly, you need to install Flask. You can do this using pip:
pip install flask
After installing Flask, here's a basic Flask application:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
In the above code, '/'
is the URL to which the home
function is bound. When you run this application and visit http://localhost:5000/
, you will see the text "Hello, World!".
Creating Routes
You can create as many routes as you like, and Flask will route to the correct view function based on the URL.
Here's an example of creating another route:
@app.route('/about')
def about():
return 'About Page'
Now, if you visit http://localhost:5000/about
, you'll see the text "About Page".
Variable Rules
You can add variable sections to a URL by marking sections with <variable_name>
. Your function then receives the <variable_name>
as a keyword argument.
Here's an example:
@app.route('/user/<username>')
def show_user_profile(username):
return 'User %s' % username
Now, if you visit http://localhost:5000/user/john
, you'll see the text "User john".
HTTP Methods
By default, a route only answers to GET requests. You can use the methods
argument of the route()
decorator to handle different HTTP methods:
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return do_the_login()
else:
return show_the_login_form()
In the above example, if the method is POST, we assume the user has submitted the login form and we should carry out the login process. If the method is GET, we assume the user wants to enter their credentials, so we present them with the login form.
Conclusion
So that's it! You've learned how to create routes in Flask, handle different HTTP methods, and utilize variable rules. Routing is one of the fundamental concepts in Flask, and mastering it will help you build effective Flask applications. Keep practicing and experimenting with different routes and methods, and you'll be a Flask pro in no time.