Skip to content

Helpers & Context

The request-scoped proxies, response shortcuts, and control-flow helpers.

current_app module-attribute

current_app = _CurrentAppProxy()

request module-attribute

request = _CurrentRequestProxy()

session module-attribute

session = _SessionProxy()

g module-attribute

g = _RequestGlobals()

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 True) - sort dict keys alphabetically. - JSONIFY_PRETTYPRINT_REGULAR (default False) - indent the output with 2 spaces for readability. Often enabled under DEBUG.

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 = HTTP_200_OK, headers: dict[str, str] | None = None, content_type: str | None = None) -> Response

Create a Response - a convenience wrapper.

Usage::

resp = make_response("Hello", 200)
resp = make_response({"data": True}, 201)

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

abort(status_code: int, detail: str = '', headers: dict[str, str] | None = None) -> NoReturn

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.

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(message: str, category: str = 'message') -> None

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

after_this_request(func: Any) -> Any

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

has_app_context() -> bool

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

has_request_context() -> bool

True iff a request is bound to this task/context.

Veloce passes the live request through arguments during dispatch, so this only flips True inside app.test_request_context() blocks or when application code explicitly sets the contextvar.

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 top-level helper.

Accepts a filesystem path (str / PathLike) and returns a FileResponse with conditional-GET headers already set (Last-Modified, ETag - both were added by Q40/Q42). Optional knobs:

  • mimetype= overrides the auto-guessed content type.
  • as_attachment=True sets Content-Disposition: attachment; filename=<download_name or basename>.
  • download_name= overrides the filename in Content-Disposition.
  • last_modified= overrides the file's mtime (datetime, unix ts, or pre-formatted IMF-fixdate string).
  • etag=False suppresses the auto-generated ETag; etag="<value>" uses the caller-provided one verbatim (already-quoted).
  • max_age= adds Cache-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

stream_with_context(generator: Any) -> Any

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.

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 numeric character references (per WHATWG HTML Sec. 13).