Helpers & Context¶
The request-scoped proxies, response shortcuts, and control-flow helpers.
jsonify
¶
jsonify(*args: Any, **kwargs: Any) -> JSONResponse
Create a JSON response - a concise shorthand.
Honours two app-config flags when called inside a request:
- JSON_SORT_KEYS (default False) - sort dict keys alphabetically.
- JSONIFY_PRETTYPRINT_REGULAR (default False) - indent the output
with 2 spaces for readability. Often enabled under DEBUG.
Both reach every JSON response, not only this helper.
Usage::
return jsonify(name="alice", age=30)
return jsonify({"name": "alice"})
return jsonify([1, 2, 3])
make_response
¶
make_response(body: Any = b'', status_code: int | None = None, headers: dict[str, str] | None = None, content_type: str | None = None) -> Response
Create a Response - a convenience wrapper.
A tuple body is unpacked as (body, status) / (body, status, headers) /
(body, headers), the same shapes a handler may return. A tuple of any other
length is not a response tuple and is answered as a plain value. The table is
_unpack_response_tuple, shared with Veloce.make_response and dispatch, so
one value cannot answer differently depending on which entry point a caller
reached for.
An omitted status_code means 200 for a plain body, and leaves an existing
Response's own status alone - make_response(resp) is a pass-through, while
make_response(resp, 403) sets 403. That is why the default is None rather
than 200: the two cases are distinguishable only if "unsupplied" has its own
value.
Usage::
resp = make_response("Hello", 200)
resp = make_response({"data": True}, 201)
resp = make_response((b"raw", 201))
resp = make_response(jsonify({"error": "forbidden"}), 403)
redirect
¶
redirect(location: str, code: int = HTTP_302_FOUND, headers: dict[str, str] | None = None) -> Response
Build a redirect response helper.
Default code=302 matches the long-standing convention. RFC 9110 Sec. 15.4
catalogue: 301 (permanent, method may change), 302 (found, method
may change), 303 (see other, method becomes GET), 307 (temporary,
method preserved), 308 (permanent, method preserved). Pick the one
that matches your semantics - the helper is a thin wrapper, not a
policy. Accepts extra headers (e.g. Vary).
abort
¶
Raise an HTTPException - a concise shorthand.
Raises the typed subclass for known status codes (e.g. NotFound for 404,
Forbidden for 403) so error handlers registered against a specific
subclass match. Unknown codes fall back to the bare HTTPException.
Inside an application context the call goes through app.aborter, so an
app that registered a custom code-to-exception mapping raises its own class
here too - abort(404) and app.aborter(404) are the same call. Outside
one, the default lookup applies.
Usage::
abort(404) # -> raises NotFound
abort(403, "Forbidden") # -> raises Forbidden
Aborter
¶
A callable that turns a status code into an HTTPException.
Used as app.aborter(404) or app.aborter(403, "Forbidden").
Subclasses can override mapping to register custom exception
classes for specific status codes; the base class leaves it empty
so the default exception_for_status lookup applies.
flash
¶
Flash a message for the next request - requires SessionMiddleware.
Usage::
flash("Item created successfully")
flash("Invalid input", "error")
get_flashed_messages
¶
get_flashed_messages(with_categories: bool = False, category_filter: Sequence[str] | None = None) -> list[str] | list[tuple[str, str]]
Get flashed messages - call in templates.
Usage::
messages = get_flashed_messages()
messages = get_flashed_messages(with_categories=True)
after_this_request
¶
Register a one-shot after-request callback.
Fires after the global @app.after_request hooks have run for the
current request only - future requests are unaffected. Useful for
work that depends on data computed inside the handler (e.g. setting
a cookie whose value the handler decided).
Returns the callback unchanged so it can be used as a decorator.
Raises RuntimeError when called outside an active request.
has_app_context
¶
True iff current_app resolves to a real app.
Use this to gate code that reads current_app/app.config so it
can also run outside a request (e.g. helper modules imported at
module-import time, before any app is bound to the contextvar).
has_request_context
¶
True iff a request is bound to this task/context.
The dispatcher binds it on every request, so this is True inside any handler,
middleware, hook or template render, as well as inside an
app.test_request_context() block. It is False outside a request - in
startup and shutdown handlers, a background task, or a CLI command.
send_file
¶
send_file(path_or_file: Any, mimetype: str | None = None, as_attachment: bool = False, download_name: str | None = None, last_modified: Any = None, etag: bool | str = True, max_age: int | None = None) -> Response
Serve a file from a filesystem path.
Accepts a str or PathLike and returns a FileResponse with the
conditional-GET headers (Last-Modified and ETag) already set. Optional
knobs:
mimetype=overrides the auto-guessed content type.as_attachment=TruesetsContent-Disposition: attachment; filename=<download_name or basename>.download_name=overrides the filename inContent-Disposition.last_modified=overrides the file's mtime (datetime, unix ts, or pre-formatted IMF-fixdate string).etag=Falsesuppresses the auto-generated ETag;etag="<value>"uses the caller-provided one verbatim (already-quoted).max_age=addsCache-Control: public, max-age=<n>.
async_send_file
async
¶
async_send_file(path_or_file: Any, mimetype: str | None = None, as_attachment: bool = False, download_name: str | None = None, last_modified: Any = None, etag: bool | str = True, max_age: int | None = None) -> Response
Serve a file - async variant of send_file.
Identical to send_file but reads the file in an executor via
FileResponse.from_path, so it never blocks the event loop. Prefer
this from async handlers; the sync send_file emits a
DeprecationWarning when called on a running loop.
send_from_directory
¶
send_from_directory(directory: str, filename: str, mimetype: str | None = None, as_attachment: bool = False, download_name: str | None = None) -> FileResponse
Send a file from a directory (sync version).
Traversal-safe via safe_join. Returns 403 on any escape attempt.
For async, use send_from_directory_async() instead.
send_from_directory_async
async
¶
send_from_directory_async(directory: str, filename: str, mimetype: str | None = None, as_attachment: bool = False, download_name: str | None = None) -> FileResponse
Send a file from a directory - async version, reads file in executor.
Traversal-safe via safe_join.
stream_with_context
¶
Keep the request context alive while a streaming generator runs.
A streaming response body is consumed by the ASGI
emit layer after the handler has returned, by which point the
request context has been torn down - so a generator that touches
request, g, or current_app would fail. Wrap it::
return StreamingResponse(stream_with_context(generate()))
The current request / app / g snapshot is captured now and
re-established for the lifetime of the wrapped iteration. Accepts
either an async or a synchronous generator/iterable.
url_for
¶
Build the URL for a named route on the active app.
The module-level form of current_app.url_for, for code that is already
inside a request and does not hold the app. Templates receive url_for
automatically, so this is for handlers and helpers.
The endpoint is positional-only, so a route may have a {endpoint} or
{name} segment and still be reversed.
Raises RuntimeError outside an application context, where there is no app
whose routing table could answer.
Markup
¶
Bases: str
A string flagged as already HTML-safe.
Equivalent to markupsafe.Markup for the subset Veloce's templating
rely on. Concatenation with a non-Markup string escapes the
other operand first so an injection cannot sneak in via +.
escape
¶
escape(value: Any) -> Markup
HTML-escape value and wrap in Markup.
Objects that implement __html__() are trusted: their return is
wrapped as-is. Otherwise the value is str()-coerced and the five
HTML-significant characters are replaced with their named or numeric
character references (per WHATWG HTML Sec. 13).