Quiz 2

Flask Introduction — Building Web Applications with Python

877 words
4 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Flask Introduction — Building Web Applications with Python ## 🎯 Learning Objectives - Set up a Flask application with routes - Create templates with Jinja2 templating engine - Use template inheritance for consistent layouts - Serve static files (CSS, JS, images) - Pass dynamic data from Python to templates ## 1....

Flask Introduction — Building Web Applications with Python

🎯 Learning Objectives

  • Set up a Flask application with routes
  • Create templates with Jinja2 templating engine
  • Use template inheritance for consistent layouts
  • Serve static files (CSS, JS, images)
  • Pass dynamic data from Python to templates

1. What is Flask?

Flask is a micro web framework for Python. "Micro" means it's lightweight — it gives you routing, templates, and request handling, but lets you choose your own tools for databases, forms, authentication, etc. It's perfect for learning web development because there's minimal magic.

2. Your First Flask App

python
# app.py — runnable
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
    return '<h1>Hello, Flask!</h1>'
@app.route('/about')
def about():
    return '<h1>About Page</h1>'
if __name__ == '__main__':
    app.run(debug=True)
Run: python app.py → Visit http://127.0.0.1:5000/ Key points:
  • Flask(__name__): Creates the Flask application
  • @app.route('/'): Decorator that maps URL to function
  • app.run(debug=True): Starts the development server with auto-reload

3. Route Patterns

python
@app.route('/user/<username>')
def show_user(username):
    return f'<h1>User: {username}</h1>'
@app.route('/post/<int:post_id>')
def show_post(post_id):
    return f'<h1>Post #{post_id}</h1>'
@app.route('/path/<path:subpath>')
def show_path(subpath):
    return f'<h1>Path: {subpath}</h1>'
Converters: string (default), int, float, path (accepts slashes), uuid.

4. Jinja2 Templates

Templates separate HTML from Python code. Create a templates/ folder:
python
from flask import render_template
@app.route('/hello/<name>')
def hello(name):
    return render_template('hello.html', name=name)
html
<!-- templates/hello.html -->
<!DOCTYPE html>
<html>
<head><title>Hello</title></head>
<body>
    <h1>Hello, {{ name }}!</h1>
</body>
</html>

Jinja2 Syntax

html
<!-- Variables -->
<p>{{ name }}</p>
<p>{{ user.name }}</p>
<p>{{ users[0] }}</p>
<!-- Filters -->
<p>{{ name|upper }}</p>          <!-- Uppercase -->
<p>{{ price|round(2) }}</p>      <!-- Round to 2 decimals -->
<p>{{ text|truncate(50) }}</p>   <!-- Truncate to 50 chars -->
<p>{{ created_at|datetimeformat }}</p>  <!-- Custom filter -->
<!-- Control flow -->
{% if user.is_admin %}
    <p>Welcome, admin!</p>
{% elif user.is_moderator %}
    <p>Welcome, moderator!</p>
{% else %}
    <p>Welcome, user!</p>
{% endif %}
<!-- Loops -->
<ul>
{% for item in items %}
    <li>{{ loop.index }}: {{ item.name }}</li>
{% endfor %}
</ul>

5. Template Inheritance

Base template (templates/base.html):
html
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}My App{% endblock %}</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <nav>
        <a href="/">Home</a>
        <a href="/about">About</a>
    </nav>
    <main>
        {% block content %}{% endblock %}
    </main>
    <footer>&copy; 2024 My App</footer>
</body>
</html>
Child template (templates/home.html):
html
{% extends "base.html" %}
{% block title %}Home - My App{% endblock %}
{% block content %}
    <h1>Welcome!</h1>
    <p>This is the home page.</p>
{% endblock %}

6. Static Files

Place files in static/ folder:
python
# In template:
<img src="{{ url_for('static', filename='logo.png') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<script src="{{ url_for('static', filename='script.js') }}"></script>
Always use url_for('static', filename='...') — it generates the correct URL path and handles versioning.

7. Flask Project Structure

java
myapp/
├── app.py              # Main application
├── requirements.txt    # Dependencies
├── static/
│   ├── css/
│   │   └── style.css
│   ├── js/
│   │   └── script.js
│   └── images/
│       └── logo.png
└── templates/
    ├── base.html
    ├── index.html
    └── about.html

8. Practice Questions

Q1: What does @app.route('/user/') do?
Answer: Maps URLs like /user/42 to the function. The <int:id> captures the number 42 as an integer and passes it as the id parameter. Q2: How do you pass data from Flask to a template?
Answer: Pass keyword arguments to render_template:
python
return render_template('profile.html', user=user, posts=posts)
In template: {{ user.name }}, {% for p in posts %}. Q3: What is template inheritance and why use it?
Answer: A base template defines the common layout (header, nav, footer). Child templates extend it and override specific blocks. This avoids duplicating HTML and ensures consistent layout across pages. Q4: What's the difference between {{ }} and {% %} in Jinja2?
Answer: {{ expression }} outputs the value (evaluated). {% statement %} executes control logic (for, if, block). {# comment #} is a comment (not rendered). Q5: How do you serve static files in Flask?
Answer: Place files in static/ directory. Reference them with {{ url_for('static', filename='css/style.css') }}. Flask automatically serves files from the static folder. Q6: What does app.run(debug=True) do?
Answer: Enables debug mode: auto-reloads the server when code changes, and shows detailed error pages with a debugger when exceptions occur. Never use in production. Q7: What is __name__ in Flask(__name__)?
Answer: It's a Python variable that tells Flask where to look for templates, static files, and the instance folder. __name__ is "__main__" for the main script, or the module name for imports. Q8: Create a Flask route that accepts a name and returns a personalized greeting.
python
@app.route('/greet/<name>')
def greet(name):
    return render_template('greet.html', name=name.upper())
Template:
html
{% extends "base.html" %}
{% block content %}
    <h1>Hello, {{ name }}!</h1>
{% endblock %}

📐 Key Concepts

ConceptCodePurpose
Route@app.route('/path')Map URL to function
Variable{{ name }}Output value in template
Block{% block name %}Extensible section
Extends{% extends "base.html" %}Template inheritance
Staticurl_for('static', fn='...')Link static files
Renderrender_template('page.html')Render template with data

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.