Skip to content

Flask — Quick tutorial

A concise, standalone Flask tutorial. Read this file to learn how to install Flask, create a minimal app, use templates and static files, organize larger apps, test, and deploy.

1. Install

Use a virtual environment.

  1. Create and activate:

python -m venv .venv source .venv/bin/activate

  1. Install Flask:

pip install Flask

If you prefer pinned dependencies, create requirements.txt and install with pip install -r requirements.txt.

2. Minimal app

Create app.py with this minimal example:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello, Flask!'

if __name__ == '__main__':
    app.run(debug=True)

Run: python app.py. The app listens on http://127.0.0.1:5000 by default.

Notes:

  • Use FLASK_APP=app.py flask run to use the Flask CLI.
  • Disable debug in production.

3. Routing and request data

Accept different HTTP verbs with methods and access request data using request:

from flask import request

@app.route('/submit', methods=['POST'])
def submit():
    name = request.form.get('name')
    return f'Received: {name}'

4. Templates (Jinja2)

Flask integrates Jinja2. Put templates in templates/.

Example templates/hello.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Hello</title>
  </head>
  <body>
    <h1>Hello, {{ name }}!</h1>
  </body>
</html>

Render from a view:

from flask import render_template

@app.route('/hello/<name>')
def hello(name):
    return render_template('hello.html', name=name)

5. Static files

Serve CSS/JS/images from static/. Reference them with url_for('static', filename='styles.css').

6. App structure and blueprints

For larger apps, use an application factory and blueprints:

  • app/init.py: create_app() factory and configuration loading.
  • app/extensions.py: initialize extensions (db, login, etc.).
  • app/blueprints/*: modular features.

Example snippet (blueprint registration):

from flask import Flask

def create_app(config=None):
    app = Flask(__name__)
    if config:
        app.config.from_mapping(config)

    from .blog import bp as blog_bp
    app.register_blueprint(blog_bp)

    return app

7. Configuration and secrets

  • Keep secrets out of source control.
  • Use environment variables and a config class or file per environment.

8. Testing

Use Flask's test client for simple unit tests:

from app import app

def test_index():
    client = app.test_client()
    resp = client.get('/')
    assert resp.status_code == 200

Run tests with pytest.

9. Deployment hints

  • Use a production WSGI server: Gunicorn or uWSGI.
  • Example: gunicorn -w 4 -b 0.0.0.0:8000 app:app
  • Serve static files via a CDN or front-end web server (nginx) for performance.
  • Ensure proper logging, monitoring, and graceful restarts.

10. Resources

  • Official docs: https://flask.palletsprojects.com/
  • Flask patterns: application factory, blueprints, keep view logic thin.