Routes , views and templates

In Flask, routes and views are core components that define how your application responds to client requests. Routes map URLs to specific functions (views), which then process the request and return a response, typically HTML, JSON, or another type of content.

Routes in Flask

Routes are defined using the @app.route decorator (or Blueprint if you're organizing your application into modular components). Each route maps a URL to a view function. Here's a detailed guide on how to define routes:

  1. Basic Route:
    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def home():
        return 'Welcome to the Home Page'
    
  2. Dynamic Routes: You can capture parts of the URL as variables and pass them to the view function.
    @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}'
    
  3. HTTP Methods: Specify the methods allowed for a route, such as GET and POST.
    @app.route('/submit', methods=['GET', 'POST'])
    def submit():
        if request.method == 'POST':
            return 'Form Submitted'
        return 'Form Page'
    
  4. Route with Query Parameters: Handle query parameters (e.g., ?page=2).
    from flask import request
    
    @app.route('/search')
    def search():
        query = request.args.get('q')
        return f'Searching for: {query}'
    
  5. Using Blueprints: For larger applications, organize routes into Blueprints.
    from flask import Blueprint
    
    bp = Blueprint('main', __name__)
    
    @bp.route('/')
    def index():
        return 'Welcome to the Main Page'
    
    @bp.route('/about')
    def about():
        return 'About Page'
    
    # Register the blueprint with the app
    app.register_blueprint(bp)
    

Views in Flask

Views are functions linked to routes that handle requests and return responses. Responses can be simple text, HTML, JSON, or other formats. They often render templates using the render_template function.

  1. Simple View:
    @app.route('/')
    def home():
        return 'Welcome to the Home Page'
    
  2. Rendering HTML Templates: Use Jinja2 templates to render HTML.
    from flask import render_template
    
    @app.route('/')
    def home():
        return render_template('index.html')
    

    In index.html (placed in the templates directory):
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Home</title>
    </head>
    <body>
        <h1>Welcome to My Flask App!</h1>
    </body>
    </html>
    
  3. Passing Data to Templates:
    @app.route('/user/<username>')
    def user_profile(username):
        return render_template('profile.html', username=username)
    

    In profile.html:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>User Profile</title>
    </head>
    <body>
        <h1>Profile Page for {{ username }}</h1>
    </body>
    </html>
    
  4. JSON Responses: Return JSON data using jsonify.
    from flask import jsonify
    
    @app.route('/api/data')
    def get_data():
        data = {'key': 'value', 'name': 'Flask'}
        return jsonify(data)
    
  5. Handling Form Data: Process data submitted via forms.
    @app.route('/submit', methods=['POST'])
    def submit():
        name = request.form['name']
        return f'Hello, {name}!'
    
  6. Error Handling: Define custom error pages.
    @app.errorhandler(404)
    def page_not_found(error):
        return render_template('404.html'), 404
    
    @app.errorhandler(500)
    def internal_error(error):
        return render_template('500.html'), 500
    

Example Project: Combining Routes and Views

Let's combine everything into a small example project:

Project Structure:

my_flask_project/
├── app/
│   ├── __init__.py
│   ├── routes.py
│   ├── templates/
│   │   ├── index.html
│   │   ├── about.html
│   │   └── profile.html
│   └── static/
├── run.py
└── config.py

app/init.py:

from flask import Flask

def create_app():
    app = Flask(__name__)
    app.config.from_object('config')

    # Import and register the blueprint
    from .routes import bp as main_bp
    app.register_blueprint(main_bp)

    return app

app/routes.py:

from flask import Blueprint, render_template, request, jsonify

bp = Blueprint('main', __name__)

@bp.route('/')
def home():
    return render_template('index.html')

@bp.route('/about')
def about():
    return render_template('about.html')

@bp.route('/user/<username>')
def user_profile(username):
    return render_template('profile.html', username=username)

@bp.route('/api/data')
def get_data():
    data = {'key': 'value', 'name': 'Flask'}
    return jsonify(data)

run.py:

from app import create_app

app = create_app()

if __name__ == '__main__':
    app.run(debug=True)

config.py:

import os

class Config:
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'

app/templates/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
</head>
<body>
    <h1>Welcome to My Flask App!</h1>
    <a href="/about">About</a>
    <a href="/user/John">John's Profile</a>
</body>
</html>

app/templates/about.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>About</title>
</head>
<body>
    <h1>About This Application</h1>
    <p>This is a simple Flask application.</p>
</body>
</html>

app/templates/profile.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User Profile</title>
</head>
<body>
    <h1>Profile Page for {{ username }}</h1>
</body>
</html>

Summary

  • Routes map URLs to view functions and can capture dynamic parts of the URL.
  • Views handle the logic of processing requests and returning responses, often rendering HTML templates or returning JSON.
  • Use Blueprints to modularize your routes and views in larger applications.

This structure provides a robust starting point for building Flask applications, enabling clean, maintainable code.