Turn requests into function calls and create, read, update and delete data.
Lectures this week
- MVC Origins
- Requests and Responses
- CRUD
- Group Actions by Controller
- Routes and Controllers
Key points, notes and past questions
Databases, SQL & Flask-SQLAlchemy
Storing data and querying it from Flask.
- Start here: tables, rows and keys from zero
- Table = grid; row = one thing; column = one fact.
- Primary key: unique in every row.
- Foreign key: another table's primary key, a link.
- NULL means no value, not 0.
- Database families, graphs and indexes
- RDBMS: tables, keys, constraints, transactions.
- Key-value: one key → one value, fastest lookups.
- Graph: nodes + edges with properties; paths matter.
- Index: faster reads, slightly slower writes.
- SQL: WHERE, GROUP BY, HAVING, ORDER BY
- WHERE → GROUP BY → HAVING → SELECT → ORDER BY.
- Aggregates per group; HAVING filters groups.
- ASC = smallest first (the default).
- No aggregates in WHERE.
- SQLite's own behaviour
- Bare columns are allowed in SQLite.
- One-row group → exact value.
- Stored text keeps its case.
- LIKE ignores ASCII case; dates are text.
- Models and column options
- Every model needs a primary key.
- nullable defaults to True; mandatory = nullable=False.
- unique ≠ NOT NULL.
- Constructor: keyword arguments only.
- Default table name: snake_case of the class.
- Foreign keys and cardinality
- Key on the many side.
- Plain key → one-to-many; unique key → one-to-one.
- Association table → many-to-many.
- Key = db.Column(type, db.ForeignKey('lowercase_table.col')).
- The session: add, commit, update
- Model(k=v) → add → commit.
- first() = one object or None; all() = list.
- Change attributes, then commit, to update.
- rollback drops uncommitted changes.
- relationship(), backref, objects and ids
- Column ← id; relationship ← object.
- backref creates the other attribute; back_populates needs both sides.
- New objects have id None until written.
- uselist=False → one object, not a list.
- Queries: filter, filter_by, aggregates and dates
- filter_by: keywords, equality, AND.
- filter: expressions with &, and_(), |, or chained.
- Never Python
and/oron conditions. - Aggregates: query(func.max(col)).scalar().
- Dates: subtract in Python, not in SQLite SQL.
Notes32 past questions in this topic
Python Fundamentals
Decorators and logging, the language features behind @app.route.
- Functions are values
- A function name is a label on a function object.
frefers to the function;f()calls it.- A closure remembers variables of the function that made it.
return wrapperreturns a function;return wrapper()would return its result.
- What @decorator does
@dabovedef fmeansf = d(f), once.- A call to
fruns the wrapper. - If the wrapper never calls
func, the original never runs. - The decorated function's
__name__is the wrapper's.
- Wrapper patterns: before, after, change, repeat
- Execute the wrapper top to bottom; the original runs where it is called.
returnis silent; onlyprintwrites a line.- A wrapper can transform the result before returning it.
- Calling
functwice runs the body twice.
- Stacked decorators
@a @b def f→f = a(b(f)).- The inner (nearest) decorator changes the result first.
- Decoration-time prints run bottom-up, once.
x / 2is always a float.
- Logging levels, format and sys.argv
- DEBUG < INFO < WARNING < ERROR < CRITICAL.
level=Xprints X and above; default threshold WARNING.- The format string is copied exactly; default is
LEVEL:root:message. sys.argv[1]is the first argument, a string.
Notes11 past questions in this topic
Flask Web Framework
How a request becomes a response in Flask, needed by the templating, REST and database chapters.
- Start here: the Python and HTTP you need, from zero
- A view is a function; its return value is the page.
- No return means None, and Flask answers 500.
- d.get(k, default) never raises; d[k] does.
- @app.route registers the function and leaves it unchanged.
- One request, one function, one response
- A route connects one path to one view function.
- The view runs only when a matching request arrives.
- No matching rule means 404, and no function runs.
- Paths are case-sensitive.
- What a view may return
- str → HTML, 200.
- dict or list → JSON, 200.
(body, status)sets the status.- No return → 500.
- Routes, stacked routes and the trailing slash
- Each
@app.routeline adds one rule; stacked lines share one function. - Rule
/x/, URL/x→ 308 redirect to/x/. - Rule
/x, URL/x/→ 404. - A path that matches no rule is 404 and no view runs.
- Each
- Dynamic parts of a URL: placeholders and converters
- A placeholder matches exactly one non-empty segment.
intaccepts digits only;floatneeds a dot;pathaccepts slashes.- A converter mismatch is a 404, not a Python error.
- The parameter name must equal the placeholder name.
- Building URLs with url_for
url_fortakes the function name, not the path.- Keyword values fill placeholders; extras go after
?. url_forreturns a string; it never runs the view.- Outside a request, wrap it in
app.test_request_context().
- Redirects
redirect(url)answers 302 with aLocationheader.- The browser then sends a new GET to that URL.
- The page shown is whatever the target route returns.
- Pass
url_foran endpoint name in quotes.
- Reading what the browser sent
- Path → route placeholders; query string →
request.args; body →request.formorrequest.get_json(). args["k"]missing → 400;args.get("k")missing →None.?kand?k=give"".- Wrong method → 405, before the view runs.
- Path → route placeholders; query string →
- abort and error handlers
abort(code, msg)stops the view at once.- The handler for the status actually raised is the one that runs.
- A handler returning a plain string sends status 200.
- 404 and 405 are raised before the view runs.
- Forms, frontend and backend validation
- GET shows the form; POST sends the fields in the body.
- HTML5 attributes = frontend validation (the browser).
ifchecks in the view = backend validation (the server).- HTML built by Python per request = dynamic, server-side rendered.
Notes39 past questions in this topic
Week 4: DatabasesWeek 6: APIs & RESTAll MAD 1 topics and weeks