Flask Full-Stack

Flask Project Structure and the App Factory

35 min

Flask is a small, flexible Python web framework. "Small" means you choose the structure, so this module gives you one that scales: the same shape PandaDev itself uses.

Install

python -m venv .venv && source .venv/bin/activate
pip install flask flask-sqlalchemy flask-migrate flask-login flask-wtf python-dotenv

Layout

myapp/
├── app/
│   ├── __init__.py        # create_app()
│   ├── extensions.py      # db, migrate, login_manager, csrf
│   ├── config.py
│   ├── models/
│   ├── routes/            # one blueprint per area
│   ├── forms/
│   ├── templates/
│   └── static/
├── migrations/
├── tests/
├── run.py                 # dev server
├── wsgi.py                # production entry point
└── requirements.txt

Extensions created once

# app/extensions.py
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_wtf import CSRFProtect

db = SQLAlchemy()
migrate = Migrate()
login_manager = LoginManager()
csrf = CSRFProtect()

Configuration from the environment

# app/config.py
import os

class Config:
    SECRET_KEY = os.environ.get("SECRET_KEY", "dev-only-change-me")
    SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL", "sqlite:///dev.db")
    SESSION_COOKIE_HTTPONLY = True
    SESSION_COOKIE_SAMESITE = "Lax"

class ProductionConfig(Config):
    SESSION_COOKIE_SECURE = True

class TestingConfig(Config):
    TESTING = True
    SQLALCHEMY_DATABASE_URI = "sqlite://"
    WTF_CSRF_ENABLED = False

The app factory

# app/__init__.py
from flask import Flask
from .extensions import db, migrate, login_manager, csrf

def create_app(config="app.config.Config"):
    app = Flask(__name__)
    app.config.from_object(config)

    db.init_app(app)
    migrate.init_app(app, db)
    login_manager.init_app(app)
    login_manager.login_view = "auth.login"
    csrf.init_app(app)

    from .routes.main import main_bp
    from .routes.auth import auth_bp
    app.register_blueprint(main_bp)
    app.register_blueprint(auth_bp, url_prefix="/auth")
    return app

A factory lets tests create fresh apps with test config, and avoids circular imports.

A blueprint

# app/routes/main.py
from flask import Blueprint, render_template
main_bp = Blueprint("main", __name__)

@main_bp.get("/")
def index():
    return render_template("index.html")

Running

# run.py
from app import create_app
app = create_app()
if __name__ == "__main__":
    app.run(debug=True)

python run.py for development. Never run debug=True in production: the debugger allows code execution.

Exercise

Create this structure with main and auth blueprints, a base template and a home page. Confirm python run.py serves it.

Check yourself

  • Why use an application factory?
  • Where should secrets come from?
  • What is a blueprint for?

Seu progresso fica salvo apenas neste navegador.

Enviar para revisão (10 pontos)