blog image

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.

1. Basic Routing

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".

3.URL Building

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.

Understanding Request Contexts in Flask

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 requestsessionurl_for(), etc.) from anywhere in your code during that request.

Why Use 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.

Example of 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:

  1. with app.test_request_context():

    • This line creates a temporary request context. Inside this block, Flask acts as if it's handling an actual HTTP request.
  2. Using url_for()

    • Inside the context, you can call 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.
  3. Accessing request Object

    • You can also access the 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.
  4. Why This is Useful

    • Imagine you're writing tests or scripts where you need to generate URLs or check request-related data. Instead of needing to send real HTTP requests, you can simply use 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:

  1. generate_search_url() Function:

    • This function generates a full URL for the /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.
  2. Simulating the Context:

    • By using app.test_request_context(), we can test this function without needing to run the Flask app or send an actual HTTP request.
  3. Output:

    • The function prints a fully generated URL like 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.

Summary:

  • 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.
  • It’s particularly useful for testing, scripting, or generating URLs dynamically without running the server.

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'

 

Introduction to Templates in Flask

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.

 

1. Creating and Using Templates

First, let's create a simple HTML template and learn how to render it using Flask.

  1. Set Up a Template Directory:

    • By default, Flask looks for templates in a folder named templates in the root directory of your project.
    • Create a folder named templates in your project directory, and inside it, create a file named index.html.
  2. 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>
      

       

 

 

 

 


About author

author image

Amrit Panta

Python developer, content writer



3 Comments

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.

Reply

Baltej 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.

Reply

Marie 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

Leave a Reply

Scroll to Top