quart.flask_patch package
Submodules
Module contents
- class quart.flask_patch.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[[Any], Any], 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[[Any], Any], 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[[Any], bool], 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[Union[RouteCallable, WebsocketCallable]] = 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 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)
- after_app_request(func: quart.blueprints.T_after_request) quart.blueprints.T_after_request
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: quart.blueprints.T_after_serving) quart.blueprints.T_after_serving
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: quart.blueprints.T_after_websocket) quart.blueprints.T_after_websocket
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 registered on. An example usage,blueprint = Blueprint(__name__) @blueprint.after_app_websocket def after(): ...
- after_request_funcs: Dict[AppOrBlueprintKey, List[AfterRequestCallable]]
- after_websocket_funcs: Dict[AppOrBlueprintKey, List[AfterWebsocketCallable]]
- app_context_processor(func: quart.blueprints.T_template_context_processor) quart.blueprints.T_template_context_processor
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[[quart.blueprints.T_error_handler], quart.blueprints.T_error_handler]
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[[quart.blueprints.T_template_filter], quart.blueprints.T_template_filter]
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[[quart.blueprints.T_template_global], quart.blueprints.T_template_global]
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[[quart.blueprints.T_template_test], quart.blueprints.T_template_test]
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: quart.blueprints.T_url_defaults) quart.blueprints.T_url_defaults
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: quart.blueprints.T_url_value_preprocessor) quart.blueprints.T_url_value_preprocessor
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: quart.blueprints.T_before_first_request) quart.blueprints.T_before_first_request
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: quart.blueprints.T_before_request) quart.blueprints.T_before_request
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: quart.blueprints.T_before_serving) quart.blueprints.T_before_serving
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: quart.blueprints.T_before_websocket) quart.blueprints.T_before_websocket
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(): ...
- before_request_funcs: Dict[AppOrBlueprintKey, List[BeforeRequestCallable]]
- before_websocket_funcs: Dict[AppOrBlueprintKey, List[BeforeWebsocketCallable]]
- deferred_functions: List[DeferredSetupFunction]
- error_handler_spec: Dict[AppOrBlueprintKey, Dict[Optional[int], Dict[Type[Exception], ErrorHandlerCallable]]]
- 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) 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.
- register_blueprint(blueprint: quart.blueprints.Blueprint, **options: Any) None
Register a
Blueprint
on this blueprint.Keyword arguments passed to this method will override the defaults set on the blueprint.
- teardown_app_request(func: quart.blueprints.T_teardown) quart.blueprints.T_teardown
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: quart.blueprints.T_teardown) quart.blueprints.T_teardown
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(): ...
- teardown_request_funcs: Dict[AppOrBlueprintKey, List[TeardownCallable]]
- teardown_websocket_funcs: Dict[AppOrBlueprintKey, List[TeardownCallable]]
- template_context_processors: Dict[AppOrBlueprintKey, List[TemplateContextProcessorCallable]]
- url_default_functions: Dict[AppOrBlueprintKey, List[URLDefaultCallable]]
- url_value_preprocessors: Dict[AppOrBlueprintKey, List[URLValuePreprocessorCallable]]
- view_functions: Dict[str, Callable]
- warn_on_modifications = False
- while_app_serving(func: quart.blueprints.T_while_serving) quart.blueprints.T_while_serving
Add a while serving function to the App.
This is designed to be used as a decorator, and has the same arguments as
while_serving()
. An example usage,@blueprint.while_serving async def func(): ... # Startup yield ... # Shutdown
- class quart.flask_patch.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) bool
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) bool
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_mapping(mapping: Optional[Mapping[str, Any]] = None, **kwargs: Any) bool
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_prefixed_env(prefix: str = 'QUART', *, loads: typing.Callable[[str], typing.Any] = <function loads>) bool
Load any environment variables that start with the prefix.
The prefix (default
QUART_
) is dropped from the env key for the config key. Values are passed through a loading function to attempt to convert them to more specific types than strings.Keys are loaded in
sorted()
order.The default loading function attempts to parse values as any valid JSON type, including dicts and lists. Specific items in nested dicts can be set by separating the keys with double underscores (
__
). If an intermediate key doesn’t exist, it will be initialized to an empty dict.- Parameters
prefix – Load env vars that start with this prefix, separated with an underscore (
_
).loads – Pass each string value to this function and use the returned value as the config value. If any error is raised it is ignored and the value remains a string. The default is
json.loads()
.
- from_pyfile(filename: str, silent: bool = False) bool
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.
- quart.flask_patch.Flask
alias of
quart.app.Quart
- class quart.flask_patch.Markup(base: Any = '', encoding: Optional[str] = None, errors: str = '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
str
. It has the same methods, but escapes their arguments and returns aMarkup
instance.>>> Markup("<em>%s</em>") % ("foo & bar",) Markup('<em>foo & bar</em>') >>> Markup("<em>Hello</em> ") + "<foo>" Markup('<em>Hello</em> <foo>')
- capitalize()
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- center(width, fillchar=' ', /)
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- classmethod escape(s: Any) markupsafe.Markup
Escape a string. Calls
escape()
and ensures that for subclasses the correct type is returned.
- expandtabs(tabsize=8)
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: Iterable[Union[str, HasHTML]]) Markup
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(width, fillchar=' ', /)
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- partition(sep: str) Tuple[markupsafe.Markup, markupsafe.Markup, markupsafe.Markup]
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(old, new, count=- 1, /)
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(width, fillchar=' ', /)
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep: str) Tuple[markupsafe.Markup, markupsafe.Markup, markupsafe.Markup]
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(sep: Optional[str] = None, maxsplit: int = - 1) List[markupsafe.Markup]
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including \n \r \t \f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits (starting from the left). -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep: Optional[str] = None, maxsplit: int = - 1) List[markupsafe.Markup]
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including \n \r \t \f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits (starting from the left). -1 (the default value) means no limit.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends: bool = False) List[markupsafe.Markup]
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(chars=None, /)
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- striptags() str
unescape()
the markup, remove tags, and normalize whitespace to single spaces.>>> Markup("Main » <em>About</em>").striptags() 'Main » About'
- swapcase()
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()
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(table, /)
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() str
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()
Return a copy of the string converted to uppercase.
- zfill(width, /)
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- class quart.flask_patch.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.
- body_class
alias of
quart.wrappers.request.Body
- property data: bytes
- property files: werkzeug.datastructures.MultiDict
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.
- property form: werkzeug.datastructures.MultiDict
The parsed form encoded data.
Note file data is present in the
files
.
- 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: Any
- lock_class
alias of
asyncio.locks.Lock
- 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 overridden) will be used as the default for any get_json calls.
- async send_push_promise(path: str) None
- property stream: NoReturn
- property values: werkzeug.datastructures.CombinedMultiDict
- class quart.flask_patch.Response(response: Optional[Union[quart.wrappers.response.ResponseBody, AnyStr, Iterable]] = None, 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.
- Type
Optional[str]
- 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: bytes
- data_body_class
alias of
quart.wrappers.response.DataBody
- default_mimetype: t.Optional[str] = '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.
- implicit_sequence_conversion = True
- io_body_class
alias of
quart.wrappers.response.IOBody
- async iter_encode() AsyncGenerator[bytes, None]
- iterable_body_class
alias of
quart.wrappers.response.IterableBody
- property json: Any
- json_module = <module 'quart.json' from '/build/quart-HrGHdM/quart-0.18.3/.pybuild/cpython3_3.11_quart/build/quart/json/__init__.py'>
- async make_conditional(request: Request, accept_ranges: Union[bool, str] = False, complete_length: Optional[int] = None) Response
- async make_sequence() None
- property max_cookie_size: int
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
- set_data(data: AnyStr) None
Set the response data.
This will encode using the
charset
.
- quart.flask_patch.abort(status: Union[int, Response], *args: Any, **kwargs: Any) te.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.flask_patch.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.flask_patch.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.flask_patch.escape()
Replace the characters
&
,<
,>
,'
, and"
in the string with HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML.If the object has an
__html__
method, it is called and the return value is assumed to already be safe for HTML.- Parameters
s – An object to be converted to a string and escaped.
- Returns
A
Markup
string with the escaped text.
- quart.flask_patch.flash(*args: Any, **kwargs: Any) Any
- quart.flask_patch.get_flashed_messages(with_categories: bool = False, category_filter: Iterable[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.flask_patch.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.flask_patch.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.flask_patch.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.flask_patch.make_response(*args: Any, **kwargs: Any) Any
- quart.flask_patch.redirect(location: str, code: int = 302, Response: Optional[Type[Response]] = None) Response
Returns a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, 307, and 308. 300 is not supported because it’s not a real redirect and 304 because it’s the answer for a request with a request with defined If-Modified-Since headers.
New in version 0.6: The location can now be a unicode string that is encoded using the
iri_to_uri()
function.New in version 0.10: The class used for the Response object can now be passed in.
- Parameters
location – the location the response should redirect to.
code – the redirect status code. defaults to 302.
Response (class) – a Response class to use when instantiating a response. The default is
werkzeug.wrappers.Response
if unspecified.
- quart.flask_patch.render_template(*args: Any, **kwargs: Any) Any
- quart.flask_patch.render_template_string(*args: Any, **kwargs: Any) Any
- quart.flask_patch.send_file(*args: Any, **kwargs: Any) Any
- quart.flask_patch.send_from_directory(*args: Any, **kwargs: Any) Any
- quart.flask_patch.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.flask_patch.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.