quart.flask_patch package

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[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 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: AfterRequestCallable)AfterRequestCallable

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: Union[Callable[], None], Callable[], Awaitable[None]]])Union[Callable[], None], Callable[], Awaitable[None]]]

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: AfterWebsocketCallable)AfterWebsocketCallable

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: Union[Callable[], Dict[str, Any]], Callable[], Awaitable[Dict[str, Any]]]])Union[Callable[], Dict[str, Any]], Callable[], Awaitable[Dict[str, Any]]]]

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[[Callable[[Any], Any]], Callable[[Any], Any]]

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[[Callable[[Any], Any]], Callable[[Any], Any]]

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[[Callable[[Any], bool]], Callable[[Any], bool]]

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[[str, dict], None])Callable[[str, dict], None]

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[[Optional[str], Optional[dict]], None])Callable[[Optional[str], Optional[dict]], None]

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: Union[Callable[], None], Callable[], Awaitable[None]]])Union[Callable[], None], Callable[], Awaitable[None]]]

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: BeforeRequestCallable)BeforeRequestCallable

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: Union[Callable[], None], Callable[], Awaitable[None]]])Union[Callable[], None], Callable[], Awaitable[None]]]

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: BeforeWebsocketCallable)BeforeWebsocketCallable

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: Union[Callable[[Optional[BaseException]], None], Callable[[Optional[BaseException]], Awaitable[None]]])Union[Callable[[Optional[BaseException]], None], Callable[[Optional[BaseException]], Awaitable[None]]]

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: Union[Callable[[Optional[BaseException]], None], Callable[[Optional[BaseException]], Awaitable[None]]])Union[Callable[[Optional[BaseException]], None], Callable[[Optional[BaseException]], Awaitable[None]]]

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
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_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)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_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 example

app.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 the FOO 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='', encoding=None, errors='strict')

Bases: markupsafe.Markup

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.

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: 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
json_module = <module 'quart.json' from '/usr/local/lib/python3.9/site-packages/Quart-0.15.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 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: 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: bytes
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: Any
json_module = <module 'quart.json' from '/usr/local/lib/python3.9/site-packages/Quart-0.15.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: Optional[str]
response: quart.wrappers.response.ResponseBody
set_data(data: AnyStr)None

Set the response data.

This will encode using the charset.

timeout: Any
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(s: Any)str
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. See flash() 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.jsonify(*args: Any, **kwargs: Any)Response
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.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.

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.