Routes map URLs to functions in your Flask app, determining how your application responds to web requests.
URL:
A URL (Uniform Resource Locator) is the web address you type into your browser. The route is the part at the end.
For example: http://www.example.com/hello
Flask:
@app.route('/hello') # Route
def say_hello(): # Function
return "Hello, visitor!"
In this example:
The URL is http://www.example.com/hello
The route is /hello
The function is say_hello()
When someone visits http://www.example.com/hello, they see "Hello, visitor!" on their screen.
Add this route to app.py:
@app.route('/')
def index():
return 'Hello, World!'
@app.route('/'): The @ symbol denotes a decorator that maps the '/' URL to the index function.
def index():: Defines the function that runs when the route is accessed.
return 'Hello, World!': Sends 'Hello, World!' as the response.
Run your app and navigate to http://127.0.0.1:5000/ to see the message.
Add this dynamic route:
@app.route('/hello/<name>')
def hello(name):
return f'Hello, {name}!'
<name>: Captures a value from the URL and passes it as the name parameter to the function.
This is called a URL parameter and allows your routes to handle different inputs without creating separate routes for each possibility.
When someone visits /hello/Alice, Flask captures "Alice" and passes it to the greet function as the name parameter.
Run your app and navigate to http://127.0.0.1:5000/hello/Alice to see the message.
Change the name in the URL and see what happens!
Add a calculator route:
@app.route('/calc/<int:num1>/<string:operation>/<int:num2>')
def calculator(num1, operation, num2):
# Program the logic of a calculator here
# E.g. if operation = "add" then result = num1 + num2
return f'{num1} {operation} {num2} = {result}'
This example uses multiple parameters in a single route.
We are also using a concept called 'type casting' in the URL. Using <int:num1> tells Flask to convert the parameter to an integer.
It shows how user input can be processed and used to generate dynamic results.
Run your app and navigate to http://127.0.0.1:5000/calc/5/add/3 to add 5 and 3.
Change the parameters and see if your calculator works in different scenarios!
Finally, let's explore how to use query parameters:
from flask import request
@app.route('/search')
def search():
query = request.args.get('q', '')
category = request.args.get('category', 'all')
return f'Searching for "{query}" in category: {category}'
Query parameters are data sent in the URL after the ? symbol. They're crucial in web development, powering everything from Google searches to complex web applications. Here's what's happening:
Web Requests: When you type a search in Google, your browser creates a URL like https://www.google.com/search?q=flask+tutorial. This is a web request - your browser asking for information from a server.
Flask Handling: In our Flask app, request.args captures these parameters. It's Flask's way of handling incoming web requests.
Accessing Data: .get('q', '') fetches the value of 'q' or uses a default (empty string) if it's missing. This is how we safely handle user input.
In the context of how the web works:
request represents the web browser asking for information.
args stands for "arguments" - the extra information in the request.
This method is part of HTTP, the language of the web.
Understanding this helps you see how websites interact with servers and is a standard way for web applications to receive user input. It's a fundamental concept in creating interactive web experiences.
Visit http://127.0.0.1:5000/search?q=flask&category=tutorial
Change the parameters and see if your search works in different scenarios!
Create a basic to-do list app. Create a file called todo.py in the terminal using touch.
You may start by using the following template:
from flask import Flask, redirect
app = Flask(__name__)
# Our "database" is just a list
todos = []
@app.route('/')
def list_todos():
# use a loop and <br> to join all to-do's into one string
# return the to-do list as one string
@app.route('/add/<task>')
def add_todo(task):
# append the 'task' to the list
# Return back to the to-do list page
return redirect('/')
@app.route('/delete/<int:task_id>')
def delete_todo(task_id):
# delete the item at the specified position in the list
# Return back to the to-do list page
return redirect('/')
if __name__ == '__main__':
app.run(debug=True)
Remember to commit and push your code when done! Here are the terminal commands to do so:
Commit your changes with a meaningful message:
git commit -am "Your message here"
Note: The -a flag automatically stages all modified files before committing, -m is to add a message.
Push your changes to GitHub:
git push origin main