Flask calls itself a "microframework," and it means it: a working web app can be a single file, yet it scales up cleanly once you split things into blueprints and packages.
pip install flask
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello, Flask'
if __name__ == '__main__':
app.run(debug=True)
The @app.route decorator maps a URL to a Python function — that mapping is the entire routing system.
Flask ships with Jinja2, which lets you keep HTML in its own files under a templates/ folder and inject Python values into it.
@app.route('/user/<name>')
def user(name):
return render_template('user.html', name=name)
<!-- templates/user.html -->
<h1>Hello, {{ name }}</h1>
{% if name == 'admin' %}
<p>Welcome back.</p>
{% endif %}
<name> in the route captures a URL segment as a function argument — no manual string parsing needed.
from flask import request
@app.route('/submit', methods=['GET', 'POST'])
def submit():
if request.method == 'POST':
name = request.form['name']
return f'Thanks, {name}'
return render_template('form.html')
By default a route only accepts GET; listing 'POST' explicitly is what lets a form submission reach it.
debug=True in production. The debugger exposes an interactive console that can execute arbitrary code if someone reaches an error page — it's a development convenience only.
Once you have more than a handful of routes, split them into blueprints — self-contained groups of routes you register onto the main app. Combined with an application factory function (create_app()), this is the standard shape for any Flask app meant to grow past a prototype.
Comments