quart package¶
Subpackages¶
Submodules¶
- quart.app module
- quart.asgi module
- quart.blueprints module
- quart.cli module
- quart.config module
- quart.ctx module
- quart.datastructures module
- quart.debug module
- quart.formparser module
- quart.globals module
- quart.helpers module
- quart.logging module
- quart.routing module
- quart.scaffold module
- quart.sessions module
- quart.signals module
- quart.templating module
- quart.typing module
- quart.utils module
- quart.views module
Module contents¶
-
class
quart.
Blueprint
(name: str, import_name: str, static_folder: Optional[str] = None, static_url_path: Optional[str] = None, template_folder: Optional[str] = None, url_prefix: Optional[str] = None, subdomain: Optional[str] = None, url_defaults: Optional[dict] = None, root_path: Optional[str] = None, cli_group: Optional[str] = Ellipsis)¶ Bases:
quart.scaffold.Scaffold
A blueprint is a collection of application properties.
The application properties include routes, error handlers, and before and after request functions. It is useful to produce modular code as it allows the properties to be defined in a blueprint thereby deferring the addition of these properties to the app.
-
url_prefix
¶ An additional prefix to every route rule in the blueprint.
-
add_app_template_filter
(func: Callable, name: Optional[str] = None) → None¶ Add an application wide template filter.
This is designed to be used on the blueprint directly, and has the same arguments as
add_template_filter()
. An example usage,def filter(): ... blueprint = Blueprint(__name__) blueprint.add_app_template_filter(filter)
-
add_app_template_global
(func: Callable, name: Optional[str] = None) → None¶ Add an application wide template global.
This is designed to be used on the blueprint directly, and has the same arguments as
add_template_global()
. An example usage,def global(): ... blueprint = Blueprint(__name__) blueprint.add_app_template_global(global)
-
add_app_template_test
(func: Callable, name: Optional[str] = None) → None¶ Add an application wide template test.
This is designed to be used on the blueprint directly, and has the same arguments as
add_template_test()
. An example usage,def test(): ... blueprint = Blueprint(__name__) blueprint.add_app_template_test(test)
-
add_url_rule
(rule: str, endpoint: Optional[str] = None, view_func: Optional[Callable] = None, *, methods: Optional[Iterable[str]] = None, defaults: Optional[dict] = None, host: Optional[str] = None, subdomain: Optional[str] = None, provide_automatic_options: Optional[bool] = None, is_websocket: bool = False, strict_slashes: Optional[bool] = None) → None¶ Add a route/url rule to the blueprint.
This is designed to be used on the blueprint directly, and has the same arguments as
add_url_rule()
. An example usage,def route(): ... blueprint = Blueprint(__name__) blueprint.add_url_rule('/', route)
-
add_websocket
(rule: str, endpoint: Optional[str] = None, view_func: Optional[Callable] = None, defaults: Optional[dict] = None, host: Optional[str] = None, subdomain: Optional[str] = None, *, strict_slashes: Optional[bool] = None) → None¶ Add a websocket rule to the blueprint.
This is designed to be used on the blueprint directly, and has the same arguments as
add_websocket()
. An example usage,def route(): ... blueprint = Blueprint(__name__) blueprint.add_websocket('/', route)
-
after_app_request
(func: Callable) → Callable¶ Add a after request function to the app.
This is designed to be used as a decorator, and has the same arguments as
after_request()
. It applies to all requests to the app this blueprint is registered on. An example usage,blueprint = Blueprint(__name__) @blueprint.after_app_request def after(): ...
-
after_app_serving
(func: Callable) → Callable¶ Add an after serving function to the App.
This is designed to be used as a decorator, and has the same arguments as
after_serving()
. An example usage,blueprint = Blueprint(__name__) @blueprint.after_app_serving def after(): ...
-
after_app_websocket
(func: Callable) → Callable¶ Add an after websocket function to the App.
This is designed to be used as a decorator, and has the same arguments as
after_websocket()
. It applies to all requests to the ppe this blueprint is registerd on. An example usage,blueprint = Blueprint(__name__) @blueprint.after_app_websocket def after(): ...
-
app_context_processor
(func: Callable) → Callable¶ Add a context processor function to the app.
This is designed to be used as a decorator, and has the same arguments as
context_processor()
. This will add context to all templates rendered. An example usage,blueprint = Blueprint(__name__) @blueprint.app_context_processor def processor(): ...
-
app_errorhandler
(error: Union[Type[Exception], int]) → Callable¶ Add an error handler function to the App.
This is designed to be used as a decorator, and has the same arguments as
errorhandler()
. It applies only to all errors. An example usage,blueprint = Blueprint(__name__) @blueprint.app_errorhandler(404) def not_found(): ...
-
app_template_filter
(name: Optional[str] = None) → Callable¶ Add an application wide template filter.
This is designed to be used as a decorator, and has the same arguments as
template_filter()
. An example usage,blueprint = Blueprint(__name__) @blueprint.app_template_filter() def filter(value): ...
-
app_template_global
(name: Optional[str] = None) → Callable¶ Add an application wide template global.
This is designed to be used as a decorator, and has the same arguments as
template_global()
. An example usage,blueprint = Blueprint(__name__) @blueprint.app_template_global() def global(value): ...
-
app_template_test
(name: Optional[str] = None) → Callable¶ Add an application wide template test.
This is designed to be used as a decorator, and has the same arguments as
template_test()
. An example usage,blueprint = Blueprint(__name__) @blueprint.app_template_test() def test(value): ...
-
app_url_defaults
(func: Callable) → Callable¶ Add a url default preprocessor.
This is designed to be used as a decorator, and has the same arguments as
url_defaults()
. This will apply to all urls. An example usage,blueprint = Blueprint(__name__) @blueprint.app_url_defaults def default(endpoint, values): ...
-
app_url_value_preprocessor
(func: Callable) → Callable¶ Add a url value preprocessor.
This is designed to be used as a decorator, and has the same arguments as
app_url_value_preprocessor()
. This will apply to all URLs. An example usage,blueprint = Blueprint(__name__) @blueprint.app_url_value_preprocessor def processor(endpoint, view_args): ...
-
before_app_first_request
(func: Callable) → Callable¶ Add a before request first function to the app.
This is designed to be used as a decorator, and has the same arguments as
before_first_request()
. It is triggered before the first request to the app this blueprint is registered on. An example usage,blueprint = Blueprint(__name__) @blueprint.before_app_first_request def before_first(): ...
-
before_app_request
(func: Callable) → Callable¶ Add a before request function to the app.
This is designed to be used as a decorator, and has the same arguments as
before_request()
. It applies to all requests to the app this blueprint is registered on. An example usage,blueprint = Blueprint(__name__) @blueprint.before_app_request def before(): ...
-
before_app_serving
(func: Callable) → Callable¶ Add a before serving to the App.
This is designed to be used as a decorator, and has the same arguments as
before_serving()
. An example usage,blueprint = Blueprint(__name__) @blueprint.before_app_serving def before(): ...
-
before_app_websocket
(func: Callable) → Callable¶ Add a before websocket to the App.
This is designed to be used as a decorator, and has the same arguments as
before_websocket()
. It applies to all requests to the app this blueprint is registered on. An example usage,blueprint = Blueprint(__name__) @blueprint.before_app_websocket def before(): ...
-
ensure_async
(func: Callable[[…], Any]) → Callable[[…], Any]¶ Ensure the function is asynchronous.
Override if you would like custom sync to async behaviour in this blueprint. Otherwise the app’s
ensure_async()
is used.
-
make_setup_state
(app: Quart, options: dict, first_registration: bool = False) → BlueprintSetupState¶ Return a blueprint setup state instance.
- Parameters
first_registration – True if this is the first registration of this blueprint on the app.
options – Keyword arguments forwarded from
register_blueprint()
.first_registration – Whether this is the first time this blueprint has been registered on the application.
-
name
: str¶
-
record
(func: Callable[[quart.blueprints.BlueprintSetupState], Callable]) → None¶ Used to register a deferred action.
-
record_once
(func: Callable[[quart.blueprints.BlueprintSetupState], Callable]) → None¶ Used to register a deferred action that happens only once.
-
register
(app: Quart, options: dict, first_registration: bool = False) → None¶ Register this blueprint on the app given.
- Parameters
app – The application this blueprint is being registered with.
options – Keyword arguments forwarded from
register_blueprint()
.first_registration – Whether this is the first time this blueprint has been registered on the application.
-
teardown_app_request
(func: Callable) → Callable¶ Add a teardown request function to the app.
This is designed to be used as a decorator, and has the same arguments as
teardown_request()
. It applies to all requests to the app this blueprint is registered on. An example usage,blueprint = Blueprint(__name__) @blueprint.teardown_app_request def teardown(): ...
-
teardown_app_websocket
(func: Callable) → Callable¶ Add a teardown websocket function to the app.
This is designed to be used as a decorator, and has the same arguments as
teardown_websocket()
. It applies to all requests to the app this blueprint is registered on. An example usage,blueprint = Blueprint(__name__) @blueprint.teardown_app_websocket def teardown(): ...
-
warn_on_modifications
= False¶
-
websocket
(rule: str, endpoint: Optional[str] = None, defaults: Optional[dict] = None, host: Optional[str] = None, subdomain: Optional[str] = None, *, strict_slashes: Optional[bool] = None) → Callable¶ Add a websocket to the blueprint.
This is designed to be used as a decorator, and has the same arguments as
websocket()
. An example usage,blueprint = Blueprint(__name__) @blueprint.websocket('/') async def route(): ...
-
-
class
quart.
Config
(root_path: Union[bytes, str, os.PathLike], defaults: Optional[dict] = None)¶ Bases:
dict
Extends a standard Python dictionary with additional load (from) methods.
Note that the convention (as enforced when loading) is that configuration keys are upper case. Whilst you can set lower case keys it is not recommended.
-
from_envvar
(variable_name: str, silent: bool = False) → None¶ Load the configuration from a location specified in the environment.
This will load a cfg file using
from_pyfile()
from the location specified in the environment, for example the two blocks below are equivalent.app.config.from_envvar('CONFIG')
filename = os.environ['CONFIG'] app.config.from_pyfile(filename)
-
from_file
(filename: str, load: Callable[[IO[Any]], Mapping], silent: bool = False) → None¶ Load the configuration from a data file.
This allows configuration to be loaded as so
app.config.from_file('config.toml', toml.load) app.config.from_file('config.json', json.load)
- Parameters
filename – The filename which when appended to
root_path
gives the path to the file.load – Callable that takes a file descriptor and returns a mapping loaded from the file.
silent – If True any errors will fail silently.
-
from_json
(filename: str, silent: bool = False) → None¶ Load the configuration values from a JSON formatted file.
This allows configuration to be loaded as so
app.config.from_json('config.json')
- Parameters
filename – The filename which when appended to
root_path
gives the path to the file.silent – If True any errors will fail silently.
-
from_mapping
(mapping: Optional[Mapping[str, Any]] = None, **kwargs: Any) → None¶ Load the configuration values from a mapping.
This allows either a mapping to be directly passed or as keyword arguments, for example,
config = {'FOO': 'bar'} app.config.from_mapping(config) app.config.form_mapping(FOO='bar')
- Parameters
mapping – Optionally a mapping object.
kwargs – Optionally a collection of keyword arguments to form a mapping.
-
from_object
(instance: Union[object, str]) → None¶ Load the configuration from a Python object.
This can be used to reference modules or objects within modules for example,
app.config.from_object('module') app.config.from_object('module.instance') from module import instance app.config.from_object(instance)
are valid.
- Parameters
instance – Either a str referencing a python object or the object itself.
-
from_pyfile
(filename: str, silent: bool = False) → None¶ Load the configuration from a Python cfg or py file.
See Python’s ConfigParser docs for details on the cfg format. It is a common practice to load the defaults from the source using the
from_object()
and then override with a cfg or py file, for exampleapp.config.from_object('config_module') app.config.from_pyfile('production.cfg')
- Parameters
filename – The filename which when appended to
root_path
gives the path to the file
-
get_namespace
(namespace: str, lowercase: bool = True, trim_namespace: bool = True) → Dict[str, Any]¶ Return a dictionary of keys within a namespace.
A namespace is considered to be a key prefix, for example the keys
FOO_A, FOO_BAR, FOO_B
are all within theFOO
namespace. This method would return a dictionary with these keys and values present.config = {'FOO_A': 'a', 'FOO_BAR': 'bar', 'BAR': False} app.config.from_mapping(config) assert app.config.get_namespace('FOO_') == {'a': 'a', 'bar': 'bar'}
- Parameters
namespace – The namespace itself (should be uppercase).
lowercase – Lowercase the keys in the returned dictionary.
trim_namespace – Remove the namespace from the returned keys.
-
-
class
quart.
Markup
(base='', encoding=None, errors='strict')¶ Bases:
str
A string that is ready to be safely inserted into an HTML or XML document, either because it was escaped or because it was marked safe.
Passing an object to the constructor converts it to text and wraps it to mark it safe without escaping. To escape the text, use the
escape()
class method instead.>>> Markup('Hello, <em>World</em>!') Markup('Hello, <em>World</em>!') >>> Markup(42) Markup('42') >>> Markup.escape('Hello, <em>World</em>!') Markup('Hello <em>World</em>!')
This implements the
__html__()
interface that some frameworks use. Passing an object that implements__html__()
will wrap the output of that method, marking it safe.>>> class Foo: ... def __html__(self): ... return '<a href="/foo">foo</a>' ... >>> Markup(Foo()) Markup('<a href="/foo">foo</a>')
This is a subclass of the text type (
str
in Python 3,unicode
in Python 2). It has the same methods as that type, but all methods escape their arguments and return aMarkup
instance.>>> Markup('<em>%s</em>') % 'foo & bar' Markup('<em>foo & bar</em>') >>> Markup('<em>Hello</em> ') + '<foo>' Markup('<em>Hello</em> <foo>')
-
capitalize
(*args, **kwargs)¶ Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
-
center
(*args, **kwargs)¶ Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
-
classmethod
escape
(s)¶ Escape a string. Calls
escape()
and ensures that for subclasses the correct type is returned.
-
expandtabs
(*args, **kwargs)¶ Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
-
format
(*args, **kwargs) → str¶ Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{‘ and ‘}’).
-
join
(seq)¶ Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
-
ljust
(*args, **kwargs)¶ Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
-
lower
(*args, **kwargs)¶ Return a copy of the string converted to lowercase.
-
lstrip
(*args, **kwargs)¶ Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
-
partition
(sep)¶ Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
-
replace
(*args, **kwargs)¶ Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
-
rjust
(*args, **kwargs)¶ Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
-
rpartition
(sep)¶ Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
-
rsplit
(*args, **kwargs)¶ Return a list of the words in the string, using sep as the delimiter string.
- sep
The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result.
- maxsplit
Maximum number of splits to do. -1 (the default value) means no limit.
Splits are done starting at the end of the string and working to the front.
-
rstrip
(*args, **kwargs)¶ Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
-
split
(*args, **kwargs)¶ Return a list of the words in the string, using sep as the delimiter string.
- sep
The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result.
- maxsplit
Maximum number of splits to do. -1 (the default value) means no limit.
-
splitlines
(*args, **kwargs)¶ Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
-
strip
(*args, **kwargs)¶ Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
unescape()
the markup, remove tags, and normalize whitespace to single spaces.>>> Markup('Main » <em>About</em>').striptags() 'Main » About'
-
swapcase
(*args, **kwargs)¶ Convert uppercase characters to lowercase and lowercase characters to uppercase.
-
title
(*args, **kwargs)¶ Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
-
translate
(*args, **kwargs)¶ Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
-
unescape
()¶ Convert escaped markup back into a text string. This replaces HTML entities with the characters they represent.
>>> Markup('Main » <em>About</em>').unescape() 'Main » <em>About</em>'
-
upper
(*args, **kwargs)¶ Return a copy of the string converted to uppercase.
-
zfill
(*args, **kwargs)¶ Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
-
-
class
quart.
Quart
(import_name: str, static_url_path: Optional[str] = None, static_folder: Optional[str] = 'static', static_host: Optional[str] = None, host_matching: bool = False, subdomain_matching: bool = False, template_folder: Optional[str] = 'templates', root_path: Optional[str] = None, instance_path: Optional[str] = None, instance_relative_config: bool = False)¶ Bases:
quart.scaffold.Scaffold
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.
-
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
-
asgi_lifespan_class
¶ The class to use to handle the ASGI lifespan protocol.
- Type
-
asgi_websocket_class
¶ The class to use to handle the ASGI websocket protocol.
- Type
-
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.
-
json_decoder
¶ The decoder for JSON data.
- Type
Optional[Type[json.decoder.JSONDecoder]]
-
json_encoder
¶ The encoder for JSON data.
- Type
Optional[Type[json.encoder.JSONEncoder]]
-
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.
Wrapper around configuration SESSION_COOKIE_NAME, use to specify the cookie name for session data.
-
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.
-
add_template_filter
(func: Callable, name: Optional[str] = None) → None¶ Add a template filter.
This is designed to be used on the application directly. An example usage,
def to_upper(value): return value.upper() app.add_template_filter(to_upper)
- Parameters
func – The function that is the filter.
name – The filter name (defaults to function name).
-
add_template_global
(func: Callable, name: Optional[str] = None) → None¶ Add a template global.
This is designed to be used on the application directly. An example usage,
def five(): return 5 app.add_template_global(five)
- Parameters
func – The function that is the global.
name – The global name (defaults to function name).
-
add_template_test
(func: Callable, name: Optional[str] = None) → None¶ Add a template test.
This is designed to be used on the application directly. An example usage,
def is_upper(value): return value.isupper() app.add_template_test(is_upper)
- Parameters
func – The function that is the test.
name – The test name (defaults to function name).
-
add_url_rule
(rule: str, endpoint: Optional[str] = None, view_func: Optional[Callable] = None, provide_automatic_options: Optional[bool] = None, *, methods: Optional[Iterable[str]] = None, defaults: Optional[dict] = None, host: Optional[str] = None, subdomain: Optional[str] = None, is_websocket: bool = False, strict_slashes: Optional[bool] = None, merge_slashes: Optional[bool] = None) → None¶ Add a route/url rule to the application.
This is designed to be used on the application directly. An example usage,
def route(): ... app.add_url_rule('/', 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.
provide_automatic_options – Optionally False to prevent OPTION handling.
methods – List of HTTP verbs the function routes.
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.route('/book', defaults={'page': 0}) @app.route('/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).
is_websocket – Whether or not the view_func is a websocket.
merge_slashes – Merge consecutive slashes to a single slash (unless as part of the path variable).
-
add_websocket
(rule: str, endpoint: Optional[str] = None, view_func: Optional[Callable] = None, defaults: Optional[dict] = None, host: Optional[str] = None, subdomain: Optional[str] = None, *, strict_slashes: Optional[bool] = None) → 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: Union[Callable[], None], Callable[], Awaitable[None]]]) → Callable[], Awaitable[None]]¶ 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
() → quart.ctx.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
quart.ctx._AppCtxGlobals
-
async
asgi_app
(scope: Union[hypercorn.typing.HTTPScope, hypercorn.typing.WebsocketScope, hypercorn.typing.LifespanScope], receive: Callable[], Awaitable[Union[hypercorn.typing.HTTPRequestEvent, hypercorn.typing.HTTPDisconnectEvent, hypercorn.typing.WebsocketConnectEvent, hypercorn.typing.WebsocketReceiveEvent, hypercorn.typing.WebsocketDisconnectEvent, hypercorn.typing.LifespanStartupEvent, hypercorn.typing.LifespanShutdownEvent]]], send: Callable[[Union[hypercorn.typing.HTTPResponseStartEvent, hypercorn.typing.HTTPResponseBodyEvent, hypercorn.typing.HTTPServerPushEvent, hypercorn.typing.HTTPDisconnectEvent, hypercorn.typing.WebsocketAcceptEvent, hypercorn.typing.WebsocketSendEvent, hypercorn.typing.WebsocketResponseStartEvent, hypercorn.typing.WebsocketResponseBodyEvent, hypercorn.typing.WebsocketCloseEvent, hypercorn.typing.LifespanStartupCompleteEvent, hypercorn.typing.LifespanStartupFailedEvent, hypercorn.typing.LifespanShutdownCompleteEvent, hypercorn.typing.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
quart.asgi.ASGIHTTPConnection
-
asgi_lifespan_class
¶ alias of
quart.asgi.ASGILifespan
-
asgi_websocket_class
¶ alias of
quart.asgi.ASGIWebsocketConnection
-
auto_find_instance_path
() → pathlib.Path¶ Locates the instance_path if it was not provided
-
before_first_request
(func: Union[Callable[], None], Callable[], Awaitable[None]]]) → Callable[], Awaitable[None]]¶ Add a before first request function.
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_first_request async def func(): ...
- Parameters
func – The before first request function itself.
-
before_serving
(func: Union[Callable[], None], Callable[], Awaitable[None]]]) → Callable[], Awaitable[None]]¶ 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.
-
config_class
¶ alias of
quart.config.Config
-
create_global_jinja_loader
() → quart.templating.DispatchingJinjaLoader¶ Create and return a global (not blueprint specific) Jinja loader.
-
create_jinja_environment
() → quart.templating.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: Optional[quart.wrappers.base.BaseRequestWebsocket]) → Optional[werkzeug.routing.MapAdapter]¶ Create and return a URL adapter.
This will create the adapter based on the request if present otherwise the app configuration.
-
property
debug
¶ Activate debug mode (extra checks, logging and reloading).
Should/must be False in production.
-
async
dispatch_request
(request_context: Optional[quart.ctx.RequestContext] = None) → Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], Union[werkzeug.datastructures.Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int, Union[werkzeug.datastructures.Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[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: Optional[quart.ctx.WebsocketContext] = None) → 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: Optional[BaseException]) → None¶ Teardown the app (context), calling the teardown functions.
-
async
do_teardown_request
(exc: Optional[BaseException], request_context: Optional[quart.ctx.RequestContext] = 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: Optional[BaseException], websocket_context: Optional[quart.ctx.WebsocketContext] = 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[[…], Any]) → Callable[[…], 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.
-
env
¶ Implements a property descriptor for objects with a config attribute.
When used as a class instance it will look up the key on the class config object, for example:
class Object: config = {} foo = ConfigAttribute('foo') obj = Object() obj.foo = 'bob' assert obj.foo == obj.config['foo']
-
async
finalize_request
(result: Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], Union[werkzeug.datastructures.Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int, Union[werkzeug.datastructures.Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], werkzeug.exceptions.HTTPException], request_context: Optional[quart.ctx.RequestContext] = None, from_error_handler: bool = False) → Union[quart.wrappers.response.Response, werkzeug.wrappers.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: Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], Union[werkzeug.datastructures.Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int, Union[werkzeug.datastructures.Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]]], websocket_context: Optional[quart.ctx.WebsocketContext] = None, from_error_handler: bool = False) → Optional[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response]]¶ 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: Optional[quart.ctx.RequestContext] = None) → Union[quart.wrappers.response.Response, werkzeug.wrappers.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: Optional[quart.ctx.WebsocketContext] = None) → Optional[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response]]¶ Adds pre and post processing to the websocket dispatching.
- Parameters
websocket_context – The websocket context, optional to match the Flask convention.
-
property
got_first_request
¶ Return if the app has received a request.
-
async
handle_exception
(error: Exception) → Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response]¶ Handle an uncaught exception.
By default this switches the error response to a 500 internal server error.
-
async
handle_http_exception
(error: werkzeug.exceptions.HTTPException) → Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response]¶ 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_request
(request: quart.wrappers.request.Request) → Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response]¶
-
handle_url_build_error
(error: Exception, endpoint: str, values: dict) → str¶ Handle a build error.
Ideally this will return a valid url given the error endpoint and values.
-
async
handle_user_exception
(error: Exception) → Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response]¶ 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
(websocket: quart.wrappers.websocket.Websocket) → Optional[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response]]¶
-
async
handle_websocket_exception
(error: Exception) → Optional[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response]]¶ Handle an uncaught exception.
By default this logs the exception and then re-raises it.
-
inject_url_defaults
(endpoint: str, values: dict) → None¶ Injects default URL values into the passed values dict.
This is used to assist when building urls, see
url_for()
.
-
iter_blueprints
() → ValuesView[quart.blueprints.Blueprint]¶ Return a iterator over the blueprints.
-
property
jinja_env
¶ The jinja environment used to load templates.
-
jinja_environment
¶ alias of
quart.templating.Environment
-
jinja_options
= {'autoescape': True, 'extensions': ['jinja2.ext.autoescape', 'jinja2.ext.with_']}¶
-
json_decoder
¶ alias of
quart.json.JSONDecoder
-
json_encoder
¶ alias of
quart.json.JSONEncoder
-
lock_class
¶ alias of
asyncio.locks.Lock
-
log_exception
(exception_info: Tuple[type, BaseException, traceback]) → None¶ Log a exception to the
logger
.By default this is only invoked for unhandled exceptions.
-
property
logger
¶ A
logging.Logger
logger for the app.This can be used to log messages in a format as defined in the app configuration, for example,
app.logger.debug("Request method %s", request.method) app.logger.error("Error, of some kind")
-
make_config
(instance_relative: bool = False) → quart.config.Config¶ Create and return the configuration with appropriate defaults.
-
async
make_default_options_response
() → quart.wrappers.response.Response¶ This is the default route function for OPTIONS requests.
-
async
make_null_session
() → quart.sessions.Session¶ Create and return a null session.
-
async
make_response
(result: Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], Union[werkzeug.datastructures.Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int, Union[werkzeug.datastructures.Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], werkzeug.exceptions.HTTPException]) → Union[quart.wrappers.response.Response, werkzeug.wrappers.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.
-
property
name
¶ The name of this application.
This is taken from the
import_name
and is used for debugging purposes.
-
open_instance_resource
(path: Union[bytes, str, os.PathLike], mode: str = 'rb') → IO¶ Open a file for reading.
Use as
with app.open_instance_resource(path) as file_: file_.read()
-
async
open_session
(request: quart.wrappers.base.BaseRequestWebsocket) → quart.sessions.Session¶ Open and return a Session using the request.
-
permanent_session_lifetime
¶ Implements a property descriptor for objects with a config attribute.
When used as a class instance it will look up the key on the class config object, for example:
class Object: config = {} foo = ConfigAttribute('foo') obj = Object() obj.foo = 'bob' assert obj.foo == obj.config['foo']
-
async
postprocess_websocket
(response: Optional[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response]], websocket_context: Optional[quart.ctx.WebsocketContext] = None) → Union[quart.wrappers.response.Response, werkzeug.wrappers.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: Optional[quart.ctx.RequestContext] = None) → Optional[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], Union[werkzeug.datastructures.Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int, Union[werkzeug.datastructures.Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]]]]¶ 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: Optional[quart.ctx.WebsocketContext] = None) → Optional[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], Union[werkzeug.datastructures.Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, AnyStr, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int, Union[werkzeug.datastructures.Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]]]]¶ 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: Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response], request_context: Optional[quart.ctx.RequestContext] = None) → Union[quart.wrappers.response.Response, werkzeug.wrappers.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.
-
property
propagate_exceptions
¶ Return true if exceptions should be propagated into debug pages.
If false the exception will be handled. See the
PROPAGATE_EXCEPTIONS
config setting.
-
register_blueprint
(blueprint: quart.blueprints.Blueprint, *, url_prefix: Optional[str] = None, url_defaults: Optional[Dict[str, Any]] = None, subdomain: Optional[str] = None, **options: Any) → None¶ Register a blueprint on the app.
This results in the blueprint’s routes, error handlers etc… being added to the app.
- Parameters
blueprint – The blueprint to register.
url_prefix – Optional prefix to apply to all paths.
url_defaults – Blueprint routes will use these default values for view arguments.
subdomain – Blueprint routes will match on this subdomain.
-
request_class
¶ alias of
quart.wrappers.request.Request
-
request_context
(request: quart.wrappers.request.Request) → quart.ctx.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.
-
response_class
¶ alias of
quart.wrappers.response.Response
-
run
(host: Optional[str] = None, port: Optional[int] = None, debug: Optional[bool] = None, use_reloader: bool = True, loop: Optional[asyncio.events.AbstractEventLoop] = None, ca_certs: Optional[str] = None, certfile: Optional[str] = None, keyfile: Optional[str] = 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: Optional[bool] = None, use_reloader: bool = True, ca_certs: Optional[str] = None, certfile: Optional[str] = None, keyfile: Optional[str] = None, shutdown_trigger: Optional[Callable[[…], Awaitable[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.
use_reloader – Automatically reload on code changes.
ca_certs – Path to the SSL CA certificate file.
certfile – Path to the SSL certificate file.
keyfile – Path to the SSL key file.
-
async
save_session
(session: quart.sessions.Session, response: Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response]) → None¶ Saves the session to the response.
-
secret_key
¶ Implements a property descriptor for objects with a config attribute.
When used as a class instance it will look up the key on the class config object, for example:
class Object: config = {} foo = ConfigAttribute('foo') obj = Object() obj.foo = 'bob' assert obj.foo == obj.config['foo']
-
select_jinja_autoescape
(filename: str) → bool¶ Returns True if the filename indicates that it should be escaped.
-
send_file_max_age_default
¶ Implements a property descriptor for objects with a config attribute.
When used as a class instance it will look up the key on the class config object, for example:
class Object: config = {} foo = ConfigAttribute('foo') obj = Object() obj.foo = 'bob' assert obj.foo == obj.config['foo']
-
session_cookie_name
¶ Implements a property descriptor for objects with a config attribute.
When used as a class instance it will look up the key on the class config object, for example:
class Object: config = {} foo = ConfigAttribute('foo') obj = Object() obj.foo = 'bob' assert obj.foo == obj.config['foo']
-
session_interface
= <quart.sessions.SecureCookieSessionInterface object>¶
-
shell_context_processor
(func: Callable[], None]) → Callable¶ Add a shell context processor.
This is designed to be used as a decorator. An example usage,
@app.shell_context_processor def additional_context(): return context
-
async
shutdown
() → None¶
-
async
startup
() → None¶
-
teardown_appcontext
(func: Union[Callable[[Optional[BaseException]], None], Callable[[Optional[BaseException]], Awaitable[None]]]) → Callable[[Optional[BaseException]], Awaitable[None]]¶ Add a teardown app (context) function.
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.teardown_appcontext async def func(): ...
- Parameters
func – The teardown function itself.
name – Optional blueprint key name.
-
template_filter
(name: Optional[str] = None) → Callable¶ Add a template filter.
This is designed to be used as a decorator. An example usage,
@app.template_filter('name') def to_upper(value): return value.upper()
- Parameters
name – The filter name (defaults to function name).
-
template_global
(name: Optional[str] = None) → Callable¶ Add a template global.
This is designed to be used as a decorator. An example usage,
@app.template_global('name') def five(): return 5
- Parameters
name – The global name (defaults to function name).
-
template_test
(name: Optional[str] = None) → Callable¶ Add a template test.
This is designed to be used as a decorator. An example usage,
@app.template_test('name') def is_upper(value): return value.isupper()
- Parameters
name – The test name (defaults to function name).
-
property
templates_auto_reload
¶ Returns True if templates should auto reload.
-
test_app
() → quart.typing.TestAppProtocol¶
-
test_app_class
¶ alias of
quart.testing.app.TestApp
-
test_cli_runner
(**kwargs: Any) → quart.testing.QuartCliRunner¶ Creates and returns a CLI test runner.
-
test_cli_runner_class
¶ alias of
quart.testing.QuartCliRunner
-
test_client
() → quart.typing.TestClientProtocol¶ Creates and returns a test client.
-
test_client_class
¶ alias of
quart.testing.client.QuartClient
-
test_request_context
(path: str, *, method: str = 'GET', headers: Optional[Union[dict, werkzeug.datastructures.Headers]] = None, query_string: Optional[dict] = None, scheme: str = 'http', send_push_promise: Callable[[str, werkzeug.datastructures.Headers], Awaitable[None]] = <function no_op_push>, data: Optional[AnyStr] = None, form: Optional[dict] = None, json: Any = <object object>, root_path: str = '', http_version: str = '1.1', scope_base: Optional[dict] = None) → quart.ctx.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.
-
testing
¶ Implements a property descriptor for objects with a config attribute.
When used as a class instance it will look up the key on the class config object, for example:
class Object: config = {} foo = ConfigAttribute('foo') obj = Object() obj.foo = 'bob' assert obj.foo == obj.config['foo']
-
trap_http_exception
(error: Exception) → bool¶ Check it error is http and should be trapped.
Trapped errors are not handled by the
handle_http_exception()
, but instead trapped by the outer most (or user handlers). This can be useful when debugging to allow tracebacks to be viewed by the debug page.
-
async
try_trigger_before_first_request_functions
() → None¶ Trigger the before first request methods.
-
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_map_class
¶ alias of
quart.routing.QuartMap
-
url_rule_class
¶ alias of
quart.routing.QuartRule
-
websocket
(rule: str, endpoint: Optional[str] = None, defaults: Optional[dict] = None, host: Optional[str] = None, subdomain: Optional[str] = None, *, strict_slashes: Optional[bool] = None) → Callable¶ 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_class
¶ alias of
quart.wrappers.websocket.Websocket
-
websocket_context
(websocket: quart.wrappers.websocket.Websocket) → quart.ctx.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.
-
-
class
quart.
Request
(method: str, scheme: str, path: str, query_string: bytes, headers: werkzeug.datastructures.Headers, root_path: str, http_version: str, scope: hypercorn.typing.HTTPScope, *, max_content_length: Optional[int] = None, body_timeout: Optional[int] = None, send_push_promise: Callable[[str, werkzeug.datastructures.Headers], Awaitable[None]])¶ Bases:
quart.wrappers.base.BaseRequestWebsocket
This class represents a request.
It can be subclassed and the subclassed used in preference by replacing the
request_class
with your subclass.-
body_class
¶ The class to store the body data within.
-
form_data_parser_class
¶ Can be overridden to implement a different form data parsing.
-
json_module
¶ A custom json decoding/encoding module, it should have dump, dumps, load, and loads methods
-
body_class
¶ alias of
quart.wrappers.request.Body
-
property
data
¶
-
property
files
¶ The parsed files.
This will return an empty multidict unless the request mimetype was
enctype="multipart/form-data"
and the method POST, PUT, or PATCH.
-
form_data_parser_class
¶ alias of
quart.formparser.FormDataParser
-
async
get_data
(cache: bool, as_text: Literal[False], parse_form_data: bool) → bytes¶ -
async
get_data
(cache: bool, as_text: Literal[True], parse_form_data: bool) → str -
async
get_data
(cache: bool = True, as_text: bool = False, parse_form_data: bool = False) → AnyStr Get the request body data.
- Parameters
cache – If False the body data will be cleared, resulting in any subsequent calls returning an empty AnyStr and reducing memory usage.
as_text – If True the data is returned as a decoded string, otherwise raw bytes are returned.
parse_form_data – Parse the data as form data first, return any remaining data.
-
async
get_json
(force: bool = False, silent: bool = False, cache: bool = True) → Any¶ Parses the body data as JSON and returns it.
- Parameters
force – Force JSON parsing even if the mimetype is not JSON.
silent – Do not trigger error handling if parsing fails, without this the
on_json_loading_failed()
will be called on error.cache – Cache the parsed JSON on this request object.
-
property
json
¶
-
json_module
= <module 'quart.json' from '/usr/local/lib/python3.9/site-packages/Quart-0.14.1-py3.9.egg/quart/json/__init__.py'>¶
-
make_form_data_parser
() → quart.formparser.FormDataParser¶
-
on_json_loading_failed
(error: Exception) → Any¶ Handle a JSON parsing error.
- Parameters
error – The exception raised during parsing.
- Returns
Any value returned (if overidden) will be used as the default for any get_json calls.
-
async
send_push_promise
(path: str) → None¶
-
property
stream
¶
-
property
values
¶
-
-
class
quart.
Response
(response: Union[quart.wrappers.response.ResponseBody, AnyStr, Iterable], status: Optional[int] = None, headers: Optional[Union[dict, werkzeug.datastructures.Headers]] = None, mimetype: Optional[str] = None, content_type: Optional[str] = None)¶ Bases:
werkzeug.sansio.response.Response
This class represents a response.
It can be subclassed and the subclassed used in preference by replacing the
response_class
with your subclass.-
automatically_set_content_length
¶ If False the content length header must be provided.
-
default_status
¶ The status code to use if not provided.
-
default_mimetype
¶ The mimetype to use if not provided.
-
implicit_sequence_conversion
¶ Implicitly convert the response to a iterable in the get_data method, to allow multiple iterations.
-
async
add_etag
(overwrite: bool = False, weak: bool = False) → None¶
-
automatically_set_content_length
= True¶
-
property
data
¶
-
data_body_class
¶ alias of
quart.wrappers.response.DataBody
-
default_mimetype
= 'text/html'¶ the default mimetype if none is provided.
-
file_body_class
¶ alias of
quart.wrappers.response.FileBody
-
async
freeze
() → None¶ Freeze this object ready for pickling.
-
async
get_data
(as_text: Literal[True]) → str¶ -
async
get_data
(as_text: Literal[False]) → bytes -
async
get_data
(as_text: bool = True) → AnyStr Return the body data.
-
async
get_json
(force: bool = False, silent: bool = False) → Any¶ Parses the body data as JSON and returns it.
- Parameters
force – Force JSON parsing even if the mimetype is not JSON.
silent – Do not trigger error handling if parsing fails, without this the
on_json_loading_failed()
will be called on error.
-
headers
: werkzeug.datastructures.Headers¶
-
implicit_sequence_conversion
= True¶
-
io_body_class
¶ alias of
quart.wrappers.response.IOBody
-
iterable_body_class
¶ alias of
quart.wrappers.response.IterableBody
-
property
json
¶
-
json_module
= <module 'quart.json' from '/usr/local/lib/python3.9/site-packages/Quart-0.14.1-py3.9.egg/quart/json/__init__.py'>¶
-
async
make_conditional
(request_range: Optional[werkzeug.datastructures.Range], max_partial_size: Optional[int] = None) → None¶ Make the response conditional to the
- Parameters
request_range – The range as requested by the request.
max_partial_size – The maximum length the server is willing to serve in a single response. Defaults to unlimited.
int([x]) -> integer int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-‘ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4
-
property
referrer
¶
-
set_data
(data: AnyStr) → None¶ Set the response data.
This will encode using the
charset
.
-
-
class
quart.
Websocket
(path: str, query_string: bytes, scheme: str, headers: werkzeug.datastructures.Headers, root_path: str, http_version: str, subprotocols: List[str], receive: Callable, send: Callable, accept: Callable, close: Callable, scope: hypercorn.typing.WebsocketScope)¶ Bases:
quart.wrappers.base.BaseRequestWebsocket
-
async
accept
(headers: Optional[Union[dict, werkzeug.datastructures.Headers]] = None, subprotocol: Optional[str] = None) → None¶ Manually chose to accept the websocket connection.
- Parameters
headers – Additional headers to send with the acceptance response.
subprotocol – The chosen subprotocol, optional.
-
async
close
(code: int, reason: str = '') → None¶
-
async
receive
() → AnyStr¶
-
async
receive_json
() → Any¶
-
property
requested_subprotocols
¶
-
async
send
(data: AnyStr) → None¶
-
async
send_json
(data: Any) → None¶
-
async
-
quart.
abort
(status: Union[int, Response], *args, **kwargs) → NoReturn¶ Raises an
HTTPException
for the given status code or WSGI application.If a status code is given, it will be looked up in the list of exceptions and will raise that exception. If passed a WSGI application, it will wrap it in a proxy WSGI exception and raise that:
abort(404) # 404 Not Found abort(Response('Hello World'))
-
quart.
after_this_request
(func: AfterRequestCallable) → AfterRequestCallable¶ Schedule the func to be called after the current request.
This is useful in situations whereby you want an after request function for a specific route or circumstance only, for example,
def index(): @after_this_request def set_cookie(response): response.set_cookie('special', 'value') return response ...
-
quart.
copy_current_app_context
(func: Callable) → Callable¶ Share the current app context with the function decorated.
The app context is local per task and hence will not be available in any other task. This decorator can be used to make the context available,
@copy_current_app_context async def within_context() -> None: name = current_app.name ...
-
quart.
copy_current_request_context
(func: Callable) → Callable¶ Share the current request context with the function decorated.
The request context is local per task and hence will not be available in any other task. This decorator can be used to make the context available,
@copy_current_request_context async def within_context() -> None: method = request.method ...
-
quart.
copy_current_websocket_context
(func: Callable) → Callable¶ Share the current websocket context with the function decorated.
The websocket context is local per task and hence will not be available in any other task. This decorator can be used to make the context available,
@copy_current_websocket_context async def within_context() -> None: method = websocket.method ...
-
quart.
escape
(s) → markup¶ Convert the characters &, <, >, ‘, and ” in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string.
-
async
quart.
flash
(message: str, category: str = 'message') → None¶ Add a message (with optional category) to the session store.
This is typically used to flash a message to a user that will be stored in the session and shown during some other request. For example,
@app.route('/login', methods=['POST']) async def login(): ... await flash('Login successful') return redirect(url_for('index'))
allows the index route to show the flashed messages, without having to accept the message as an argument or otherwise. See
get_flashed_messages()
for message retrieval.
-
quart.
get_flashed_messages
(with_categories: bool = False, category_filter: List[str] = []) → Union[List[str], List[Tuple[str, str]]]¶ Retrieve the flashed messages stored in the session.
This is mostly useful in templates where it is exposed as a global function, for example
<ul> {% for message in get_flashed_messages() %} <li>{{ message }}</li> {% endfor %} </ul>
Note that caution is required for usage of
category_filter
as all messages will be popped, but only those matching the filter returned. Seeflash()
for message creation.
-
quart.
get_template_attribute
(template_name: str, attribute: str) → Any¶ Load a attribute from a template.
This is useful in Python code in order to use attributes in templates.
- Parameters
template_name – To load the attribute from.
attribute – The attribute name to load
-
quart.
has_app_context
() → bool¶ Check if execution is within an app context.
This allows a controlled way to act if there is an app context available, or silently not act if not. For example,
if has_app_context(): log.info("Executing in %s context", current_app.name)
See also
has_request_context()
-
quart.
has_request_context
() → bool¶ Check if execution is within a request context.
This allows a controlled way to act if there is a request context available, or silently not act if not. For example,
if has_request_context(): log.info("Request endpoint %s", request.endpoint)
See also
has_app_context()
.
-
quart.
has_websocket_context
() → bool¶ Check if execution is within a websocket context.
This allows a controlled way to act if there is a websocket context available, or silently not act if not. For example,
if has_websocket_context(): log.info("Websocket endpoint %s", websocket.endpoint)
See also
has_app_context()
.
-
async
quart.
make_push_promise
(path: str) → None¶ Create a push promise, a simple wrapper function.
This takes a path that should be pushed to the client if the protocol is HTTP/2.
-
async
quart.
make_response
(*args: Any) → Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response]¶ Create a response, a simple wrapper function.
This is most useful when you want to alter a Response before returning it, for example
response = make_response(render_template('index.html')) response.headers['X-Header'] = 'Something'
-
async
quart.
render_template
(template_name_or_list: Union[str, List[str]], **context: Any) → str¶ Render the template with the context given.
- Parameters
template_name_or_list – Template name to render of a list of possible template names.
context – The variables to pass to the template.
-
async
quart.
render_template_string
(source: str, **context: Any) → str¶ Render the template source with the context given.
- Parameters
source – The template source code.
context – The variables to pass to the template.
-
quart.
safe_join
(directory: Union[bytes, str, os.PathLike], *paths: Union[bytes, str, os.PathLike]) → pathlib.Path¶ Safely join the paths to the known directory to return a full path.
- Raises
NotFound – if the full path does not share a commonprefix with
the directory. –
-
async
quart.
send_file
(filename_or_io: Union[bytes, str, os.PathLike, _io.BytesIO], mimetype: Optional[str] = None, as_attachment: bool = False, attachment_filename: Optional[str] = None, add_etags: bool = True, cache_timeout: Optional[int] = None, conditional: bool = False, last_modified: Optional[datetime.datetime] = None) → quart.wrappers.response.Response¶ Return a Response to send the filename given.
- Parameters
filename_or_io – The filename (path) to send, remember to use
safe_join()
.mimetype – Mimetype to use, by default it will be guessed or revert to the DEFAULT_MIMETYPE.
as_attachment – If true use the attachment filename in a Content-Disposition attachment header.
attachment_filename – Name for the filename, if it differs
add_etags – Set etags based on the filename, size and modification time.
last_modified – Used to override the last modified value.
cache_timeout – Time in seconds for the response to be cached.
-
async
quart.
send_from_directory
(directory: Union[bytes, str, os.PathLike], file_name: str, *, mimetype: Optional[str] = None, as_attachment: bool = False, attachment_filename: Optional[str] = None, add_etags: bool = True, cache_timeout: Optional[int] = None, conditional: bool = True, last_modified: Optional[datetime.datetime] = None) → quart.wrappers.response.Response¶ Send a file from a given directory.
- Parameters
directory – Directory that when combined with file_name gives the file path.
file_name – File name that when combined with directory gives the file path.
See
send_file()
for the other arguments.
-
quart.
stream_with_context
(func: Callable) → Callable¶ Share the current request context with a generator.
This allows the request context to be accessed within a streaming generator, for example,
@app.route('/') def index() -> AsyncGenerator[bytes, None]: @stream_with_context async def generator() -> bytes: yield request.method.encode() yield b' ' yield request.path.encode() return generator()
-
quart.
url_for
(endpoint: str, *, _anchor: Optional[str] = None, _external: Optional[bool] = None, _method: Optional[str] = None, _scheme: Optional[str] = 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.