Install Flask, define your first routes, return HTML templates with Jinja2, and understand the request/response objects.
pip install flask
mkdir my-app && cd my-appfrom flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
@app.route('/')
def index():
name = request.args.get('name', 'World')
return render_template('index.html', name=name)
@app.route('/hello/')
def hello(username):
return f'Hello, {username}!'
@app.route('/submit', methods=['GET', 'POST'])
def submit():
if request.method == 'POST':
data = request.form.get('message')
return redirect(url_for('index'))
return render_template('form.html')
if __name__ == '__main__':
app.run(debug=True)
Flask App
Hello, {{ name }}!
{% if name != 'World' %}
Nice to meet you, {{ name }}.
{% endif %}
{% for item in items %}
{{ item }}
{% endfor %}
Home
url_for('view_name') to generate URLs in templates and code. Never hardcode /submit. If the URL changes, url_for still works. Hardcoded URLs break silently.@app.route('/path') maps a URL to a Python function.render_template('file.html', key=value) renders Jinja2 templates with context.request.args = query params. request.form = POST form data.url_for('function_name') generates URLs. Always use it instead of hardcoding.