Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Flask Routing and Templates

1. Introduction

Flask is a lightweight WSGI web application framework in Python. One of its core features is the ability to handle routing and templates, which are essential for developing dynamic web applications.

2. Flask Routing

Routing in Flask allows you to map URLs to functions (view functions). When a user requests a specific URL, Flask will call the associated function.

Key Concepts

  • Route: A URL pattern that Flask recognizes.
  • View Function: A function that executes when a route is matched.

Basic 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)

Dynamic Routing

You can also define dynamic routes that accept variable parts in the URL.

@app.route('/user/')
def show_user_profile(username):
    return f"User: {username}"

3. Flask Templates

Templates in Flask are used to create HTML dynamically. Flask uses Jinja2 as its templating engine.

Setting Up Templates

Templates are typically stored in a folder named templates within your project directory.

Rendering Templates

from flask import render_template

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

Using Template Variables

You can pass variables to templates:

@app.route('/user/')
def show_user_profile(username):
    return render_template('user.html', username=username)

Example Template (user.html)

<!DOCTYPE html>
<html>
<head><title>User Profile</title></head>
<body>
    <h1>User: {{ username }}</h1>
</body>
</html>

4. Best Practices

  • Keep routes simple and readable.
  • Use descriptive names for view functions.
  • Organize templates in a dedicated folder.
  • Utilize template inheritance for layout consistency.

5. FAQ

What is Flask?

Flask is a lightweight web framework for Python, designed to make web development easy and quick.

How do I install Flask?

You can install Flask using pip: pip install Flask

What is Jinja2?

Jinja2 is the templating engine used by Flask to create dynamic HTML pages.