patera¶
The top-level package: the application class, configuration, requests, responses and helpers.
Patera
¶
Bases: Injectable, Generic[ConfT]
Patera class implementation. Used to create a new application instance
Init function
controllers
property
¶
controllers: dict[str, Controller]
Registered controller instances by controller class name.
json_spec
property
¶
OpenAPI specification of the app (built on first access).
url_prefix
property
¶
The URL_PREFIX setting: the prefix of every controller route ('' for none).
app
property
¶
Returns self.
For compatibility with the Controller class, which contains the app object on the app property.
request_class
property
¶
request_class: Type[Request]
Returns the Request class used by the application. Can be overridden in configs.
response_class
property
¶
response_class: Type[Response]
Returns the Response class used by the application. Can be overridden in configs.
extensions
property
¶
Returns dictionary with all registered extensions.
get_conf
¶
Returns app configuration with provided config_name.
Dotted names ("DATABASE.URI") read nested attributes or mapping keys.
Returns default if the configuration is missing or None.
abort_route_not_found
async
¶
Aborts request because route was not found.
abort_method_not_allowed
async
¶
Aborts request because method is not allowed.
redirect_request
async
¶
Send an HTTP redirect response.
send_response
async
¶
send_response(res: Response, send, response_type: Optional[Type[Any]] = None)
Sends response.
Serialization is delegated to the response renderer / serializer registry. This method focuses on transport concerns: - zero-copy responses - streaming responses - normal ASGI start/body sending
add_request_observer
¶
Calls observer(record) with a RequestRecord after every HTTP
request, including those answered by the router (404, 405), static
resources and failed requests. Observers run in the request's task
once its response has been sent, so they must be quick and must not
block; an observer that raises is logged and skipped.
default_exception_response
¶
Fallback responses for exceptions without a registered handler.
BaseHttpException subclasses (abort(), RequestValidationError from @consumes, auth exceptions, ...) become a JSON response with the exception's status code.
Returns None for any other exception, which is then treated as an unhandled error (500). That includes a Pydantic ValidationError raised outside request-body validation: it is the server's data that failed. Override in the app class to customize.
register_middleware
¶
register_middleware(middleware_class: Type[MiddlewareBase], *, order: int | None = None) -> None
Registers a middleware class with the application.
Middleware instances are not created immediately. They are instantiated only when the HTTP application is built.
This allows extensions to register middleware during app initialization without forcing the HTTP app to build in CLI mode.
build
¶
Build the final app by wrapping self._app in all middleware.
Lower middleware order values are processed first and become outer middleware.
get_extension
¶
Returns a registered extension by class.
Example: db_manager = app.get_extension(SqlDatabaseManager)
register_controller
¶
register_controller(*ctrls: type[Controller], with_url_prefix: bool = True)
Registers controller classes with the application. Their routes get the URL_PREFIX setting in front unless with_url_prefix is False.
get_controller
¶
get_controller(ctrl: type[Controller] | str) -> Optional[Controller]
Returns the registered controller instance for a controller class (or class name), or None if it is not registered.
register_exception_handler
¶
register_exception_handler(*handlers: type[ExceptionHandler])
Registers exception handler classes with the application.
A handler class that is already registered is skipped. A different class with the same name raises ValueError.
add_on_shutdown_method
¶
Adds method to on_shutdown collection.
register_alias
¶
Registers an alias for an endpoint name. Useful for url_for lookups.
cli_commands
¶
cli_commands() -> list[CLICommand]
Lists every registered CLI command, sorted by name.
print_cli_commands
¶
Prints the registered CLI commands with their arguments and help.
run_cli
¶
Runs the command command_name, written as
<controller>:<command>. An invalid name, an unknown controller
or an unknown command prints an error to standard error and exits
with status 1.
add_template_path
¶
Adds a template path (searched after the already registered ones).
add_template_prefix
¶
Makes the templates in path available as "
on_startup
¶
Decorated methods will run in alphabetical order on app startup
on_shutdown
¶
Decorated methods will run in alphabetical order on app shutdown
BaseConfig
¶
Bases: BaseSettings
value_to_bool
staticmethod
¶
Turns a boolean-like value to boolean.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
a string value representing a boolean Returns True if value in [True, "true", "True", "1", 1] |
required |
BaseExtension
¶
Bases: Injectable, Generic[AppT, ConfT]
configs
property
¶
Returns the extension's configuration instance.
The configuration is looked up by the extension's UPPER_SNAKE_CASE class name. Dictionaries are validated with the declared config model and a missing configuration falls back to the model's defaults.
Request
¶
Request(scope: dict, receive: Callable[..., Any], send: Callable[..., Any], app: 'Patera', route_parameters: dict, route_handler: Callable)
ASGI-style request adapter that lazy-parses JSON, form, and multipart.
response_started
property
¶
True once the response's status and headers have been sent. After that, an error can no longer be answered with an error response.
headers
property
¶
Request headers by lower-case name. A header sent several times is combined into one comma-separated value, as RFC 9110 allows; repeated Cookie headers are joined with "; ". Use header_list() for the separate values.
cookies
property
¶
Cookies sent with the request, by name. Malformed cookie pairs are skipped rather than failing the request.
query_parameters
property
¶
Query parameters by name. A parameter given once is a string, one given several times a list; blank values are kept as "". Use query_list() to always get a list.
max_content_length
property
writable
¶
Largest body, in bytes, this request may send; None means no limit.
Defaults to the MAX_CONTENT_LENGTH setting. A middleware or a before-request hook can raise or lower it for one request, for example on an upload endpoint, before the body is read.
query_list
¶
Every value of a query parameter (an empty list if absent).
validate
¶
Validates data the client sent, which the handler reads itself (query parameters, route values, a header), with a Pydantic model:
query = req.validate(SearchQuery, req.query_parameters)
Invalid data raises RequestValidationError, answered with 422 like an invalid @consumes body. A ValidationError raised any other way is the server's own data failing and is answered with 500.
body
async
¶
Reads and returns the whole request body.
Raises RequestBodyTooLarge (413) when the declared Content-Length or
the bytes actually received exceed max_content_length. The
declared length is checked first, so an oversized upload is refused
before it is read.
json
async
¶
Parses the body as JSON and caches the result.
Returns None for an empty body. Malformed JSON raises
InvalidRequestBody (400); a body over max_content_length raises
RequestBodyTooLarge (413).
form_list
async
¶
Every value of a form field (an empty list if absent).
UploadedFile
¶
Wrapper around an in-memory/temporary file.
read
¶
Reads like a file: from the current position, up to size bytes
(everything that is left without a size), and moves the position on.
An empty result means the end was reached, so chunked readers such as
shutil.copyfileobj() work. Use seek(0) to read again from the start.
Response
¶
Bases: Generic[U]
Response object of the application. Holds status code, headers, body, stream and rendering metadata.
Example:
status_set
property
¶
True if the status was set with status() (or a builder that sets it).
content_type
property
¶
Gets the raw Content-Type header value, if present.
redirect
¶
redirect(location: str, status_code: int | HttpStatus = SEE_OTHER) -> Self
Redirects the client to the provided location.
json
¶
Creates a JSON response from Python data (a dictionary, list, model, ...). Actual JSON serialization is done later by a serializer.
Strings and bytes raise TypeError: whether "hello" is meant as text or as an already encoded document is ambiguous, and sending it as it is would not be valid JSON. Use text() for text, or bytes(data, MediaType.APPLICATION_JSON.value) for JSON that is already encoded.
problem
¶
problem(title: str, detail: str, status: int | HttpStatus, type_: str = 'about:blank', instance: str | None = None, extra: Optional[dict[str, Any]] = None) -> Self
Creates an RFC 7807 / RFC 9457 style problem response.
text
¶
Creates a plain text response. Encoding is done later by a serializer.
html_body
¶
Creates an HTML response from an already-rendered HTML string.
ndjson
¶
Creates an NDJSON response: one JSON record per line.
A list, tuple or other sized collection is serialized in one piece by
the NDJSON serializer. A generator, iterator or async iterator is
streamed: each record is serialized and sent as soon as it is
produced, so large exports never sit in memory. In both cases
dictionaries are validated through the handler's Response[Model]
annotation when it names a Pydantic model.
html_from_string
async
¶
Renders an HTML string as a Jinja template and stores the rendered HTML as response body.
html
async
¶
Renders an HTML template and stores the rendered HTML as response body.
template_path: relative path of template inside the templates folder context: dictionary with data used in the template
set_header
¶
Sets or updates a normal header in the response.
Note: - Set-Cookie must be handled through set_cookie() or delete_cookie().
set_headers
¶
Sets multiple normal headers in the response.
add_raw_cookie
¶
Adds a prebuilt Set-Cookie header value.
Example: response.add_raw_cookie("session=abc; Path=/; HttpOnly; Secure")
set_cookie
¶
set_cookie(cookie_name: str, value: str, max_age: int | None = None, path: str = '/', domain: str | None = None, secure: bool = False, http_only: bool = True, same_site: str | None = 'Lax') -> Self
Adds a Set-Cookie header to the response.
cookie_name: Cookie name value: Cookie value max_age: Max age of the cookie in seconds path: Path where the cookie is available domain: Domain where the cookie is available secure: Cookie is sent only over HTTPS http_only: Cookie is inaccessible to JavaScript same_site: SameSite policy: 'Lax', 'Strict' or 'None' (any case)
Raises ValueError for a name or value that a browser would not accept unchanged (spaces, ";", ",", quotes, backslashes or control characters; encode such values first, for example with base64), and for SameSite=None without Secure, which browsers reject.
delete_cookie
¶
delete_cookie(cookie_name: str, path: str = '/', domain: str | None = None, same_site: str | None = 'Lax', secure: bool = False) -> Self
Deletes a cookie by sending a Set-Cookie header with Max-Age=0 and a past Expires value.
Use the same path, domain and SameSite/Secure settings the cookie was set with; a cookie set with SameSite=None needs secure=True here too.
reset
¶
Resets all outgoing response state.
This is useful before building an error response after a handler or serializer failure. It prevents partially prepared headers, cookies, body data, streams, redirects, and file-send metadata from leaking into the final error response.
The app and request references are intentionally preserved.
stream
¶
Creates a streaming response for bytes.
stream_text
¶
stream_text(iterable: AsyncIterable[str] | Iterable[str], media_type: str = value, charset: str = 'utf-8') -> Self
Creates a streaming text response.
RequestRecord
dataclass
¶
RequestRecord(method: str, path: str, route: Optional[str], status_code: Optional[int], started_at: float, duration: float)
One finished HTTP request, passed to every request observer.
route is the matched URL rule, such as /api/exams/<exam_id>, so
requests to the same endpoint share it; it is None when no route matched
(404, 405, trailing-slash redirects). status_code is the status the
response started with, 500 when the request failed before a response
started, and None when the client left before any response.
abort
¶
abort(msg: str, status_code: int | HttpStatus = BAD_REQUEST, status: str = 'error', data: Any = None)
Aborts request by raising an aborter exception
html_abort
¶
html_abort(template: str, status_code: int | HttpStatus = BAD_REQUEST, data: Any = None)
Aborts request with html response
run_in_background
¶
Fire-and-forget a function (async or sync) without awaiting its result.
Important: - Detached background tasks should not rely on request-scoped context. - Pass only the data the task needs. - If database access is needed, open a fresh session inside the task.
run_sync_or_async
async
¶
Runs an async callable directly and a sync callable in a worker thread. A sync callable that returns an awaitable (a lambda returning a coroutine, for example) has that awaitable awaited too.
development
¶
Decorator to mark a controller/cli controller/middleware/logger or endpoint method as development only. The decorated class or endpoint will be ignored and unreachable if the application is not in DEBUG=True mode.
ignore
¶
Decorator to mark a controller/cli controller/middleware/logger as ignored. The decorated class will be ignored during startup and runtime.
MediaType
¶
Bases: StrEnum
HttpMethod
¶
Bases: StrEnum
All allowed http methods
HttpStatus
¶
Bases: IntEnum
LogLevel
¶
Bases: StrEnum