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, which reach every JSON response and not only
this helper: JSON_SORT_KEYS sorts dict keys, and
JSONIFY_PRETTYPRINT_REGULAR indents the output with 2 spaces.
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; any other length is
answered as a plain value. An omitted status_code means 200 for a plain
body and leaves an existing Response's own status alone, which is why the
default is None rather than 200.
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.
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).
abort
¶
Raise an HTTPException - a concise shorthand.
Raises the typed subclass for known status codes so a handler registered
against that subclass matches; unknown codes fall back to HTTPException.
Inside an application context the call goes through app.aborter, so a
custom code-to-exception mapping applies here too.
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
override mapping to register custom exception classes per status code.
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, for the current request
only. Returns the callback unchanged so it can be used as a decorator, and
raises RuntimeError outside an active request.
has_app_context
¶
True iff current_app resolves to a real app.
Use it to gate code that reads current_app / app.config so it can also
run outside a request.
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.
Reads the file in an executor, so it never blocks the event loop. Prefer it
from async handlers; the sync send_file warns 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 body is consumed after the handler returns, by which point the
request context has been torn down. The current request / app / g snapshot
is captured now and re-established for the wrapped iteration, which may be
an async or a synchronous generator::
return StreamingResponse(stream_with_context(generate()))
url_for
¶
Build the URL for a named route on the active app.
The module-level form of current_app.url_for. The endpoint is
positional-only, so a route may have an {endpoint} or {name} segment and
still be reversed. Raises RuntimeError outside an application context.
Markup
¶
Bases: str
A string flagged as already HTML-safe.
Concatenation with a non-Markup string escapes the other operand first, so
an injection cannot sneak in via +.