quart.app module#
- class quart.app.Quart(import_name: str, static_url_path: str | None = None, static_folder: str | None = 'static', static_host: str | None = None, host_matching: bool = False, subdomain_matching: bool = False, template_folder: str | None = 'templates', instance_path: str | None = None, instance_relative_config: bool = False, root_path: str | None = None)#
Bases:
App
The web framework class, handles requests and returns responses.
The primary method from a serving viewpoint is
handle_request()
, from an application viewpoint all the other methods are vital.This can be extended in many ways, with most methods designed with this in mind. Additionally any of the classes listed as attributes can be replaced.
- aborter_class#
The class to use to raise HTTP error via the abort helper function.
- app_ctx_globals_class#
The class to use for the
g
object
- asgi_http_class#
The class to use to handle the ASGI HTTP protocol.
- Type:
type[ASGIHTTPProtocol]
- asgi_lifespan_class#
The class to use to handle the ASGI lifespan protocol.
- Type:
type[ASGILifespanProtocol]
- asgi_websocket_class#
The class to use to handle the ASGI websocket protocol.
- Type:
type[ASGIWebsocketProtocol]
- config_class#
The class to use for the configuration.
- env#
The name of the environment the app is running on.
- debug#
Wrapper around configuration DEBUG value, in many places this will result in more output if True. If unset, debug mode will be activated if environ is set to ‘development’.
- jinja_environment#
The class to use for the jinja environment.
- jinja_options#
The default options to set when creating the jinja environment.
- permanent_session_lifetime#
Wrapper around configuration PERMANENT_SESSION_LIFETIME value. Specifies how long the session data should survive.
- request_class#
The class to use for requests.
- response_class#
The class to user for responses.
- secret_key#
Warpper around configuration SECRET_KEY value. The app secret for signing sessions.
- session_interface#
The class to use as the session interface.
- url_map_class#
The class to map rules to endpoints.
- url_rule_class#
The class to use for URL rules.
- websocket_class#
The class to use for websockets.
- aborter_class#
alias of
Aborter
- add_background_task(func: Callable, *args: Any, **kwargs: Any) None #
- add_websocket(rule: str, endpoint: str | None = None, view_func: Callable[[...], Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int, Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] | None] | Callable[[...], Awaitable[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int, Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] | None]] | None = None, **options: Any) None #
Add a websocket url rule to the application.
This is designed to be used on the application directly. An example usage,
def websocket_route(): ... app.add_websocket('/', websocket_route)
- Parameters:
rule – The path to route on, should start with a
/
.endpoint – Optional endpoint name, if not present the function name is used.
view_func – Callable that returns a response.
defaults –
A dictionary of variables to provide automatically, use to provide a simpler default path for a route, e.g. to allow for
/book
rather than/book/0
,@app.websocket('/book', defaults={'page': 0}) @app.websocket('/book/<int:page>') def book(page): ...
host – The full host name for this route (should include subdomain if needed) - cannot be used with subdomain.
subdomain – A subdomain for this specific route.
strict_slashes – Strictly match the trailing slash present in the path. Will redirect a leaf (no slash) to a branch (with slash).
- after_serving(func: T_after_serving) T_after_serving #
Add a after serving function.
This will allow the function provided to be called once after anything is served (after last byte is sent).
This is designed to be used as a decorator, if used to decorate a synchronous function, the function will be wrapped in
run_sync()
and run in a thread executor (with the wrapped function returned). An example usage,@app.after_serving async def func(): ...
- Parameters:
func – The function itself.
- app_context() AppContext #
Create and return an app context.
This is best used within a context, i.e.
async with app.app_context(): ...
- app_ctx_globals_class#
alias of
_AppCtxGlobals
- async asgi_app(scope: HTTPScope | WebsocketScope | LifespanScope, receive: Callable[[], Awaitable[HTTPRequestEvent | HTTPDisconnectEvent | WebsocketConnectEvent | WebsocketReceiveEvent | WebsocketDisconnectEvent | LifespanStartupEvent | LifespanShutdownEvent]], send: Callable[[HTTPResponseStartEvent | HTTPResponseBodyEvent | HTTPServerPushEvent | HTTPEarlyHintEvent | HTTPDisconnectEvent | WebsocketAcceptEvent | WebsocketSendEvent | WebsocketResponseStartEvent | WebsocketResponseBodyEvent | WebsocketCloseEvent | LifespanStartupCompleteEvent | LifespanStartupFailedEvent | LifespanShutdownCompleteEvent | LifespanShutdownFailedEvent], Awaitable[None]]) None #
This handles ASGI calls, it can be wrapped in middleware.
When using middleware with Quart it is preferable to wrap this method rather than the app itself. This is to ensure that the app is an instance of this class - which allows the quart cli to work correctly. To use this feature simply do,
app.asgi_app = middleware(app.asgi_app)
- asgi_http_class#
alias of
ASGIHTTPConnection
- asgi_lifespan_class#
alias of
ASGILifespan
- asgi_websocket_class#
alias of
ASGIWebsocketConnection
- before_serving(func: T_before_serving) T_before_serving #
Add a before serving function.
This will allow the function provided to be called once before anything is served (before any byte is received).
This is designed to be used as a decorator, if used to decorate a synchronous function, the function will be wrapped in
run_sync()
and run in a thread executor (with the wrapped function returned). An example usage,@app.before_serving async def func(): ...
- Parameters:
func – The function itself.
- create_jinja_environment() Environment #
Create and return the jinja environment.
This will create the environment based on the
jinja_options
and configuration settings. The environment will include the Quart globals by default.
- create_url_adapter(request: BaseRequestWebsocket | None) MapAdapter | None #
Create and return a URL adapter.
This will create the adapter based on the request if present otherwise the app configuration.
- default_config: dict = {'APPLICATION_ROOT': None, 'BACKGROUND_TASK_SHUTDOWN_TIMEOUT': 5, 'BODY_TIMEOUT': 60, 'DEBUG': None, 'ENV': None, 'MAX_CONTENT_LENGTH': 16777216, 'MAX_COOKIE_SIZE': 4093, 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(days=31), 'PREFER_SECURE_URLS': False, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'PROPAGATE_EXCEPTIONS': None, 'RESPONSE_TIMEOUT': 60, 'SECRET_KEY': None, 'SEND_FILE_MAX_AGE_DEFAULT': datetime.timedelta(seconds=43200), 'SERVER_NAME': None, 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_SAMESITE': None, 'SESSION_COOKIE_SECURE': False, 'SESSION_REFRESH_EACH_REQUEST': True, 'TEMPLATES_AUTO_RELOAD': None, 'TESTING': False, 'TRAP_BAD_REQUEST_ERRORS': None, 'TRAP_HTTP_EXCEPTIONS': False}#
- async dispatch_request(request_context: RequestContext | None = None) Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int, Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] #
Dispatch the request to the view function.
- Parameters:
request_context – The request context, optional as Flask omits this argument.
- async dispatch_websocket(websocket_context: WebsocketContext | None = None) Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int, Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] | None #
Dispatch the websocket to the view function.
- Parameters:
websocket_context – The websocket context, optional to match the Flask convention.
- async do_teardown_appcontext(exc: BaseException | None) None #
Teardown the app (context), calling the teardown functions.
- async do_teardown_request(exc: BaseException | None, request_context: RequestContext | None = None) None #
Teardown the request, calling the teardown functions.
- Parameters:
exc – Any exception not handled that has caused the request to teardown.
request_context – The request context, optional as Flask omits this argument.
- async do_teardown_websocket(exc: BaseException | None, websocket_context: WebsocketContext | None = None) None #
Teardown the websocket, calling the teardown functions.
- Parameters:
exc – Any exception not handled that has caused the websocket to teardown.
websocket_context – The websocket context, optional as Flask omits this argument.
- ensure_async(func: Callable[[P], Any]) Callable[[P], Awaitable[Any]] #
Ensure that the returned func is async and calls the func.
New in version 0.11.
Override if you wish to change how synchronous functions are run. Before Quart 0.11 this did not run the synchronous code in an executor.
- async finalize_request(result: Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int, Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] | HTTPException, request_context: RequestContext | None = None, from_error_handler: bool = False) Response | Response #
Turns the view response return value into a response.
- Parameters:
result – The result of the request to finalize into a response.
request_context – The request context, optional as Flask omits this argument.
- async finalize_websocket(result: Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int, Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] | HTTPException, websocket_context: WebsocketContext | None = None, from_error_handler: bool = False) Response | Response | None #
Turns the view response return value into a response.
- Parameters:
result – The result of the websocket to finalize into a response.
websocket_context – The websocket context, optional as Flask omits this argument.
- async full_dispatch_request(request_context: RequestContext | None = None) Response | Response #
Adds pre and post processing to the request dispatching.
- Parameters:
request_context – The request context, optional as Flask omits this argument.
- async full_dispatch_websocket(websocket_context: WebsocketContext | None = None) Response | Response | None #
Adds pre and post processing to the websocket dispatching.
- Parameters:
websocket_context – The websocket context, optional to match the Flask convention.
- get_send_file_max_age(filename: str | None) int | None #
Used by
send_file()
to determine themax_age
cache value for a given file path if it wasn’t passed.By default, this returns
SEND_FILE_MAX_AGE_DEFAULT
from the configuration ofcurrent_app
. This defaults toNone
, which tells the browser to use conditional requests instead of a timed cache, which is usually preferable.Note this is a duplicate of the same method in the Quart class.
- async handle_background_exception(error: Exception) None #
- async handle_exception(error: Exception) Response | Response #
Handle an uncaught exception.
By default this switches the error response to a 500 internal server error.
- async handle_http_exception(error: HTTPException) HTTPException | Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int, Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] #
Handle a HTTPException subclass error.
This will attempt to find a handler for the error and if fails will fall back to the error response.
- async handle_user_exception(error: Exception) HTTPException | Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int, Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] #
Handle an exception that has been raised.
This should forward
HTTPException
tohandle_http_exception()
, then attempt to handle the error. If it cannot it should reraise the error.
- async handle_websocket_exception(error: Exception) Response | Response | None #
Handle an uncaught exception.
By default this logs the exception and then re-raises it.
- jinja_environment#
alias of
Environment
- lock_class#
alias of
Lock
- log_exception(exception_info: tuple[type, BaseException, TracebackType] | tuple[None, None, None]) None #
Log a exception to the
logger
.By default this is only invoked for unhandled exceptions.
- async make_default_options_response() Response #
This is the default route function for OPTIONS requests.
- async make_response(result: Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int, Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] | HTTPException) Response | Response #
Make a Response from the result of the route handler.
- The result itself can either be:
A Response object (or subclass).
A tuple of a ResponseValue and a header dictionary.
A tuple of a ResponseValue, status code and a header dictionary.
A ResponseValue is either a Response object (or subclass) or a str.
- make_shell_context() dict #
Create a context for interactive shell usage.
The
shell_context_processors
can be used to add additional context.
- async open_instance_resource(path: bytes | str | PathLike, mode: str = 'rb') AiofilesContextManager[None, None, AsyncBufferedReader] #
Open a file for reading.
Use as
async with await app.open_instance_resource(path) as file_: await file_.read()
- async open_resource(path: bytes | str | PathLike, mode: str = 'rb') AiofilesContextManager[None, None, AsyncBufferedReader] #
Open a file for reading.
Use as
async with await app.open_resource(path) as file_: await file_.read()
- async postprocess_websocket(response: Response | Response | None, websocket_context: WebsocketContext | None = None) Response | Response #
Postprocess the websocket acting on the response.
- Parameters:
response – The response after the websocket is finalized.
websocket_context – The websocket context, optional as Flask omits this argument.
- async preprocess_request(request_context: RequestContext | None = None) Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int, Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] | None #
Preprocess the request i.e. call before_request functions.
- Parameters:
request_context – The request context, optional as Flask omits this argument.
- async preprocess_websocket(websocket_context: WebsocketContext | None = None) Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int] | Tuple[Response | Response | bytes | str | Mapping[str, Any] | List[Any] | Iterator[bytes] | Iterator[str], int, Headers | Mapping[str, str | List[str] | Tuple[str, ...]] | Sequence[Tuple[str, str | List[str] | Tuple[str, ...]]]] | None #
Preprocess the websocket i.e. call before_websocket functions.
- Parameters:
websocket_context – The websocket context, optional as Flask omits this argument.
- async process_response(response: Response | Response, request_context: RequestContext | None = None) Response | Response #
Postprocess the request acting on the response.
- Parameters:
response – The response after the request is finalized.
request_context – The request context, optional as Flask omits this argument.
- raise_routing_exception(request: BaseRequestWebsocket) NoReturn #
- request_context(request: Request) RequestContext #
Create and return a request context.
Use the
test_request_context()
whilst testing. This is best used within a context, i.e.async with app.request_context(request): ...
- Parameters:
request – A request to build a context around.
- run(host: str | None = None, port: int | None = None, debug: bool | None = None, use_reloader: bool = True, loop: AbstractEventLoop | None = None, ca_certs: str | None = None, certfile: str | None = None, keyfile: str | None = None, **kwargs: Any) None #
Run this application.
This is best used for development only, see Hypercorn for production servers.
- Parameters:
host – Hostname to listen on. By default this is loopback only, use 0.0.0.0 to have the server listen externally.
port – Port number to listen on.
debug – If set enable (or disable) debug mode and debug output.
use_reloader – Automatically reload on code changes.
loop – Asyncio loop to create the server in, if None, take default one. If specified it is the caller’s responsibility to close and cleanup the loop.
ca_certs – Path to the SSL CA certificate file.
certfile – Path to the SSL certificate file.
keyfile – Path to the SSL key file.
- run_task(host: str = '127.0.0.1', port: int = 5000, debug: bool | None = None, ca_certs: str | None = None, certfile: str | None = None, keyfile: str | None = None, shutdown_trigger: Callable[[...], Awaitable[None]] | None = None) Coroutine[None, None, None] #
Return a task that when awaited runs this application.
This is best used for development only, see Hypercorn for production servers.
- Parameters:
host – Hostname to listen on. By default this is loopback only, use 0.0.0.0 to have the server listen externally.
port – Port number to listen on.
debug – If set enable (or disable) debug mode and debug output.
ca_certs – Path to the SSL CA certificate file.
certfile – Path to the SSL certificate file.
keyfile – Path to the SSL key file.
- session_interface = <quart.sessions.SecureCookieSessionInterface object>#
- async shutdown() None #
- async startup() None #
- sync_to_async(func: Callable[[P], T]) Callable[[P], Awaitable[T]] #
Return a async function that will run the synchronous function func.
This can be used as so,:
result = await app.sync_to_async(func)(*args, **kwargs)
Override this method to change how the app converts sync code to be asynchronously callable.
- test_app() TestAppProtocol #
- test_cli_runner(**kwargs: Any) QuartCliRunner #
Creates and returns a CLI test runner.
- test_cli_runner_class#
alias of
QuartCliRunner
- test_client(use_cookies: bool = True) TestClientProtocol #
Creates and returns a test client.
- test_client_class#
alias of
QuartClient
- test_request_context(path: str, *, method: str = 'GET', headers: dict | ~werkzeug.datastructures.headers.Headers | None = None, query_string: dict | None = None, scheme: str = 'http', send_push_promise: ~typing.Callable[[str, ~werkzeug.datastructures.headers.Headers], ~typing.Awaitable[None]] = <function no_op_push>, data: AnyStr | None = None, form: dict | None = None, json: ~typing.Any = <object object>, root_path: str = '', http_version: str = '1.1', scope_base: dict | None = None, auth: ~werkzeug.datastructures.auth.Authorization | tuple[str, str] | None = None, subdomain: str | None = None) RequestContext #
Create a request context for testing purposes.
This is best used for testing code within request contexts. It is a simplified wrapper of
request_context()
. It is best used in a with block, i.e.async with app.test_request_context("/", method="GET"): ...
- Parameters:
path – Request path.
method – HTTP verb
headers – Headers to include in the request.
query_string – To send as a dictionary, alternatively the query_string can be determined from the path.
scheme – Scheme for the request, default http.
- async update_template_context(context: dict) None #
Update the provided template context.
This adds additional context from the various template context processors.
- Parameters:
context – The context to update (mutate).
- url_for(endpoint: str, *, _anchor: str | None = None, _external: bool | None = None, _method: str | None = None, _scheme: str | None = None, **values: Any) str #
Return the url for a specific endpoint.
This is most useful in templates and redirects to create a URL that can be used in the browser.
- Parameters:
endpoint – The endpoint to build a url for, if prefixed with
.
it targets endpoint’s in the current blueprint._anchor – Additional anchor text to append (i.e. #text).
_external – Return an absolute url for external (to app) usage.
_method – The method to consider alongside the endpoint.
_scheme – A specific scheme to use.
values – The values to build into the URL, as specified in the endpoint rule.
- websocket(rule: str, **options: Any) Callable[[T_websocket], T_websocket] #
Add a websocket to the application.
This is designed to be used as a decorator, if used to decorate a synchronous function, the function will be wrapped in
run_sync()
and run in a thread executor (with the wrapped function returned). An example usage,@app.websocket('/') async def websocket_route(): ...
- Parameters:
rule – The path to route on, should start with a
/
.endpoint – Optional endpoint name, if not present the function name is used.
defaults –
A dictionary of variables to provide automatically, use to provide a simpler default path for a route, e.g. to allow for
/book
rather than/book/0
,@app.websocket('/book', defaults={'page': 0}) @app.websocket('/book/<int:page>') def book(page): ...
host – The full host name for this route (should include subdomain if needed) - cannot be used with subdomain.
subdomain – A subdomain for this specific route.
strict_slashes – Strictly match the trailing slash present in the path. Will redirect a leaf (no slash) to a branch (with slash).
- websocket_context(websocket: Websocket) WebsocketContext #
Create and return a websocket context.
Use the
test_websocket_context()
whilst testing. This is best used within a context, i.e.async with app.websocket_context(websocket): ...
- Parameters:
websocket – A websocket to build a context around.
- while_serving(func: T_while_serving) T_while_serving #
Add a while serving generator function.
This will allow the generator provided to be invoked at startup and then again at shutdown.
This is designed to be used as a decorator. An example usage,
@app.while_serving async def func(): ... # Startup yield ... # Shutdown
- Parameters:
func – The function itself.