Flask Web Applications & Templates
Build lightweight and flexible web apps using the Flask micro-framework.
Hello Flask
Flask is a micro-framework because it doesn't require particular tools or libraries. It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
Routing
Routes are used to bind a function to a URL.
@app.route('/user/<username>')
def show_user_profile(username):
return f'User {username}'
def show_user_profile(username):
return f'User {username}'
Rendering Templates (Jinja2)
Flask uses the Jinja2 template engine to render HTML files.
from flask import render_template
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
Sample Template (hello.html)
<!doctype html>
<title>Hello from Flask</title>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello, World!</h1>
{% endif %}
<title>Hello from Flask</title>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello, World!</h1>
{% endif %}
Handling Forms
Access form data using the request object.
from flask import request
@app.route('/login', methods=['POST', 'GET'])
def login():
if request.method == 'POST':
username = request.form['username']
return f'Logging in {username}'
return '''<form method="post">...</form>'''
@app.route('/login', methods=['POST', 'GET'])
def login():
if request.method == 'POST':
username = request.form['username']
return f'Logging in {username}'
return '''<form method="post">...</form>'''
โ Practice (30 minutes)
- Install Flask:
pip install flask. - Create a simple app with 3 routes: Home, About, and Contact.
- Use a shared
base.htmltemplate with navigation and content blocks. - Create a route that accepts a dynamic
idand fetches data (mocked) for that ID.