pip install flask★Install the framework into your venv.export FLASK_APP=app.pyTell the CLI which module holdsapp.flask run★Start the dev server on :5000.app.run(debug=True)Or run directly withpython app.py; auto-reload + debugger.debug=Truedev onlyNever ship the debugger to production.
from flask import Flask★Import the class that builds an app.app = Flask(__name__)★__name__tells Flask where to find templates/static.@app.route('/')★
def index(): ...The smallest possible Flask app — one route.
app.config['DEBUG'] = TrueSet one key directly.app.config.from_pyfile('config.py')Load settings from a separate file.app.config.from_object(DevelopmentConfig)★Load from a Python class — easiest to swap per-env.class BaseConfig:
SECRET_KEY = os.environ.get('SECRET_KEY')
class DevelopmentConfig(BaseConfig):
DEBUG = TrueObject-based config: a base class + per-env subclasses.
@app.route('/')★GET by default.@app.route('/login', methods=['GET','POST'])★Allow multiple HTTP verbs on one rule.if request.method == 'POST':Branch inside the view by verb.url_for('index')Build a URL from a view's function name — never hardcode paths.
@app.route('/user/<name>')★String segment captured as an argument (default type).@app.route('/page/<int:pg_num>')★Typed converter:int,float,path,uuid.def user(name):
return f'User: {name}'Captured variables are passed as view arguments.
from flask import request★Thread-local proxy for the current request.request.args★Query-string params, e.g.?q=flask.request.form★Submitted form-encoded fields.request.json★Parsed JSON body of the request.request.filesUploaded file objects.request.cookiesCookies sent by the client.
return 'Hello'★Plain string → 200 OK, text/html.jsonify(message='Hello')★Dict/kwargs → proper JSON response + headers.make_response('Custom', 200)Build a response object you can mutate (headers, cookies).res.headers['X-Test'] = 'True'Attach a custom header before returning.return 'Not found', 404★Tuple form: body, status code.
render_template('home.html', posts=posts)★Render a file fromtemplates/with variables in scope.{{ name }}★Print a variable.{% for p in posts %} ... {% endfor %}Loop over a list passed from the view.{{ body|upper }}Filters transform values:upper,length, custom ones too.{% extends "base.html" %}★Inherit a shared layout; fill namedblocks.{% include "_post.html" %}Drop in a reusable partial.
<link href="{{ url_for('static', filename='css/style.css') }}">★Always link static assets throughurl_for, not a raw path.static/Default folder Flask serves automatically at/static/....
app.secret_key = 'secret'★Required to sign the session cookie.session['user'] = 'admin'★Store data across requests for one client.resp.set_cookie('site', 'Flask')Set a plain (unsigned) cookie on a response.SECRET_KEYkeep secretLoad from an env var in production — never hardcode.
@app.before_requestRun before every view (auth checks, logging).@app.after_request
def after(res): return resMutate every outgoing response.@app.errorhandler(404)★Custom handler for a given HTTP status.
admin = Blueprint('admin', __name__, url_prefix='/admin')★A self-contained group of routes/templates.@admin.route('/')Define routes on the blueprint, same as onapp.app.register_blueprint(admin)★Wire it into the main app — once, in the factory.
db = SQLAlchemy()★One shared instance, attached to the app later.class Post(db.Model):★
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String(256))A model maps to a table; columns map to fields.db.init_app(app)Bind the db instance to this app (insideapp_context()).db.create_all()★Create tables for all defined models.db.session.add(p); db.session.commit()★Stage + persist a new row.Post.query.all()★Fetch every row as model instances.
migrate = Migrate(app, db)Wire Alembic-based migrations into the app.flask db initCreate themigrations/folder — once per project.flask db migrate★Auto-generate a migration script from model changes.flask db upgrade★Apply pending migrations to the database.
login_manager = LoginManager()Manages the logged-in user across requests.@login_manager.user_loader★
def load_user(uid): ...Tells Flask-Login how to reload a user by id.@app.shell_context_processorPre-import objects (db, models) intoflask shell.$ flask shellInteractive console with app context already pushed.
DEBUGEnables the interactive debugger + reloader.SECRET_KEYSigns sessions and secure cookies.SQLALCHEMY_DATABASE_URIConnection string, e.g.sqlite:///data.db.SQLALCHEMY_TRACK_MODIFICATIONSSetFalse— silences a deprecation overhead.TESTINGEnables testing-mode error propagation.