In this tutorial we will learn about below topices
Routing: Understanding URLs and defining routes.
Templates: Using Jinja2 templates to render HTML.
Static Files: Serving CSS, JavaScript, and images.
Forms: Handling user input with Flask forms.
Understanding Routing in Flask
Let's dive into routing in Flask, which is a core concept for building web applications.
Routing is the process of matching a URL to a function in your Flask application. When a user visits a particular URL, Flask looks at the route you've defined and calls the corresponding function.
In Flask, you define routes using the @app.route() decorator. Here's a simple example:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Welcome to the Home Page!'
@app.route('/about')
def about():
return 'This is the About Page.'
if __name__ == '__main__':
app.run(debug=True)

@app.route('/'): This route maps the root URL (/) to the home function. When you visit http://127.0.0.1:5000/, it will display "Welcome to the Home Page!".@app.route('/about'): This route maps the /about URL to the about function. When you visit http://127.0.0.1:5000/about, it will display "This is the About Page."2. Dynamic Routing
Flask also allows you to create dynamic routes that accept parameters. For example:
@app.route('/user/<username>')
def show_user_profile(username):
return f'User: {username}'
@app.route('/post/<int:post_id>')
def show_post(post_id):
return f'Post ID: {post_id}'
<username>: A dynamic part of the URL. When you visit http://127.0.0.1:5000/user/john, it will display "User: john".<int:post_id>: Here, post_id is expected to be an integer. When you visit http://127.0.0.1:5000/post/1, it will display "Post ID: 1".Flask provides a url_for() function to dynamically build URLs. This is useful when you want to avoid hardcoding URLs in your templates or code.
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def home():
return 'Home Page'
@app.route('/login')
def login():
return 'Login Page'
@app.route('/user/<username>')
def profile(username):
return f'Profile page of {username}'
if __name__ == '__main__':
with app.test_request_context():
print(url_for('home'))
print(url_for('login'))
print(url_for('profile', username='john'))
app.run(debug=True)
url_for('home'): This builds the URL for the home function. It would output /.url_for('login'): This builds the URL for the login function. It would output /login.url_for('profile', username='john'): This builds the URL for the profile function with the username parameter. It would output /user/john.concept of app.test_request_context():
The app.test_request_context() is a context manager in Flask that allows you to simulate a request context, enabling you to test parts of your Flask application that require an active request context without actually running the server or making an HTTP request.
Flask uses a concept called context to manage the current state of a request. When Flask handles a request, it pushes a request context, which includes things like the request object, onto the stack. This context allows you to access request-related variables (like request, session, url_for(), etc.) from anywhere in your code during that request.
app.test_request_context()?Sometimes, you might need to use functions like url_for() or access the request object outside of an actual HTTP request (e.g., during testing or in a script). Since these functions rely on the request context being active, you can use app.test_request_context() to create a temporary request context.
app.test_request_context()Let's explore this with a more detailed example:
from flask import Flask, url_for, request
app = Flask(__name__)
@app.route('/')
def home():
return 'Home Page'
@app.route('/login')
def login():
return 'Login Page'
@app.route('/user/<username>')
def profile(username):
return f'Profile page of {username}'
if __name__ == '__main__':
# Simulate a request context to use url_for() without running the server
with app.test_request_context():
# Now you can use url_for() and other context-dependent functions
print(url_for('home')) # Outputs: /
print(url_for('login')) # Outputs: /login
print(url_for('profile', username='john')) # Outputs: /user/john
# Access the request object in the simulated context
print(request.path) # Outputs: /
# Start the Flask application
app.run(debug=True)
Explanation:
with app.test_request_context():
Using url_for()
url_for() just as you would inside a view function. This is useful for testing what the generated URLs will look like without needing to start the server or navigate to those pages in a browser.Accessing request Object
request object inside this block. For example, request.path gives you the path of the current request, which is / in this case because no specific route was accessed in the simulated context.Why This is Useful
app.test_request_context() to simulate the request context.
from flask import Flask, url_for, request
app = Flask(__name__)
@app.route('/search')
def search():
query = request.args.get('q', '')
return f'Search results for: {query}'
def generate_search_url(query):
with app.test_request_context():
return url_for('search', q=query, _external=True)
if __name__ == '__main__':
# Test the generate_search_url function
search_url = generate_search_url('flask')
print(search_url) # Outputs: http://localhost:5000/search?q=flask
# Start the Flask application
app.run(debug=True)
Explanation:
generate_search_url() Function:
/search route with a query parameter. The _external=True argument in url_for() tells Flask to generate an absolute URL, including the scheme (http/https) and host.Simulating the Context:
app.test_request_context(), we can test this function without needing to run the Flask app or send an actual HTTP request.Output:
http://localhost:5000/search?q=flask, demonstrating how you can use app.test_request_context() to simulate different aspects of a request context for testing purposes.app.test_request_context() allows you to simulate a request context so you can use functions like url_for() or access the request object outside of an actual HTTP request.4. HTTP Methods in Routing
By default, Flask routes handle only GET requests, but you can specify which methods a route should handle using the methods parameter:
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return 'Handling POST request'
else:
return 'Handling GET request'
Templates allow you to separate the presentation logic from your Python code. In Flask, you use templates to dynamically generate HTML pages based on the data you pass to them. Flask uses Jinja2 as its default templating engine.
First, let's create a simple HTML template and learn how to render it using Flask.
Set Up a Template Directory:
templates in the root directory of your project.templates in your project directory, and inside it, create a file named index.html.Creating index.html:
Here’s a simple HTML template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home Page</title>
</head>
<body>
<h1>{{ title }}</h1>
<p>Welcome to {{ name }}'s website!</p>
</body>
</html>
Amanda Martines 5 days ago
Exercitation photo booth stumptown tote bag Banksy, elit small batch freegan sed. Craft beer elit seitan exercitation, photo booth et 8-bit kale chips proident chillwave deep v laborum. Aliquip veniam delectus, Marfa eiusmod Pinterest in do umami readymade swag. Selfies iPhone Kickstarter, drinking vinegar jean.
ReplyBaltej Singh 5 days ago
Drinking vinegar stumptown yr pop-up artisan sunt. Deep v cliche lomo biodiesel Neutra selfies. Shorts fixie consequat flexitarian four loko tempor duis single-origin coffee. Banksy, elit small.
ReplyMarie Johnson 5 days ago
Kickstarter seitan retro. Drinking vinegar stumptown yr pop-up artisan sunt. Deep v cliche lomo biodiesel Neutra selfies. Shorts fixie consequat flexitarian four loko tempor duis single-origin coffee. Banksy, elit small.
Reply