index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
29,209 | efficientnet | init_keras_custom_objects | null | def init_keras_custom_objects():
import keras
from . import model
custom_objects = {
'swish': inject_keras_modules(model.get_swish)(),
'FixedDropout': inject_keras_modules(model.get_dropout)()
}
try:
keras.utils.generic_utils.get_custom_objects().update(custom_objects)
except AttributeError:
keras.utils.get_custom_objects().update(custom_objects)
| () |
29,210 | efficientnet | init_tfkeras_custom_objects | null | def init_tfkeras_custom_objects():
import tensorflow.keras as tfkeras
from . import model
custom_objects = {
'swish': inject_tfkeras_modules(model.get_swish)(),
'FixedDropout': inject_tfkeras_modules(model.get_dropout)()
}
tfkeras.utils.get_custom_objects().update(custom_objects)
| () |
29,211 | efficientnet | inject_keras_modules | null | def inject_keras_modules(func):
import keras
@functools.wraps(func)
def wrapper(*args, **kwargs):
kwargs['backend'] = keras.backend
kwargs['layers'] = keras.layers
kwargs['models'] = keras.models
kwargs['utils'] = keras.utils
return func(*args, **kwargs)
return wrapper
| (func) |
29,212 | efficientnet | inject_tfkeras_modules | null | def inject_tfkeras_modules(func):
import tensorflow.keras as tfkeras
@functools.wraps(func)
def wrapper(*args, **kwargs):
kwargs['backend'] = tfkeras.backend
kwargs['layers'] = tfkeras.layers
kwargs['models'] = tfkeras.models
kwargs['utils'] = tfkeras.utils
return func(*args, **kwargs)
return wrapper
| (func) |
29,213 | quart.blueprints | Blueprint | 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.
| class Blueprint(SansioBlueprint):
"""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.
"""
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
super().__init__(*args, **kwargs)
self.cli = AppGroup()
self.cli.name = self.name
self.after_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[AfterWebsocketCallable]] = (
defaultdict(list)
)
self.before_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[BeforeWebsocketCallable]] = (
defaultdict(list)
)
self.teardown_websocket_funcs: dict[AppOrBlueprintKey, list[TeardownCallable]] = (
defaultdict(list)
)
def get_send_file_max_age(self, filename: str | None) -> int | None:
"""Used by :func:`send_file` to determine the ``max_age`` cache
value for a given file path if it wasn't passed.
By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
the configuration of :data:`~flask.current_app`. This defaults
to ``None``, which tells the browser to use conditional requests
instead of a timed cache, which is usually preferable.
Note this is a duplicate of the same method in the Quart
class.
"""
value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]
if value is None:
return None
if isinstance(value, timedelta):
return int(value.total_seconds())
return value
return None
async def send_static_file(self, filename: str) -> Response:
if not self.has_static_folder:
raise RuntimeError("No static folder for this object")
return await send_from_directory(self.static_folder, filename)
async def open_resource(
self,
path: FilePath,
mode: str = "rb",
) -> AiofilesContextManager[None, None, AsyncBufferedReader]:
"""Open a file for reading.
Use as
.. code-block:: python
async with await app.open_resource(path) as file_:
await file_.read()
"""
if mode not in {"r", "rb", "rt"}:
raise ValueError("Files can only be opened for reading")
return async_open(os.path.join(self.root_path, path), mode) # type: ignore
def websocket(
self,
rule: str,
**options: t.Any,
) -> t.Callable[[T_websocket], T_websocket]:
"""Add a websocket to the application.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.websocket('/')
async def websocket_route():
...
Arguments:
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``,
.. code-block:: python
@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).
"""
def decorator(func: T_websocket) -> T_websocket:
endpoint = options.pop("endpoint", None)
self.add_websocket(
rule,
endpoint,
func,
**options,
)
return func
return decorator
def add_websocket(
self,
rule: str,
endpoint: str | None = None,
view_func: WebsocketCallable | None = None,
**options: t.Any,
) -> None:
"""Add a websocket url rule to the application.
This is designed to be used on the application directly. An
example usage,
.. code-block:: python
def websocket_route():
...
app.add_websocket('/', websocket_route)
Arguments:
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``,
.. code-block:: python
@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).
"""
return self.add_url_rule(
rule,
endpoint,
view_func,
methods={"GET"},
websocket=True,
**options,
)
@setupmethod
def before_websocket(
self,
func: T_before_websocket,
) -> T_before_websocket:
"""Add a before websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.before_websocket
async def func():
...
Arguments:
func: The before websocket function itself.
"""
self.before_websocket_funcs[None].append(func)
return func
@setupmethod
def after_websocket(
self,
func: T_after_websocket,
) -> T_after_websocket:
"""Add an after websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.after_websocket
async def func(response):
return response
Arguments:
func: The after websocket function itself.
"""
self.after_websocket_funcs[None].append(func)
return func
@setupmethod
def teardown_websocket(
self,
func: T_teardown,
) -> T_teardown:
"""Add a teardown websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.teardown_websocket
async def func():
...
Arguments:
func: The teardown websocket function itself.
name: Optional blueprint key name.
"""
self.teardown_websocket_funcs[None].append(func)
return func
@setupmethod
def before_app_websocket(self, func: T_before_websocket) -> 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 :meth:`~quart.Quart.before_websocket`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_websocket
def before():
...
"""
self.record_once(lambda state: state.app.before_websocket(func)) # type: ignore
return func
@setupmethod
def before_app_serving(self, func: T_before_serving) -> 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 :meth:`~quart.Quart.before_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_serving
def before():
...
"""
self.record_once(lambda state: state.app.before_serving(func)) # type: ignore
return func
@setupmethod
def after_app_websocket(self, func: T_after_websocket) -> 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 :meth:`~quart.Quart.after_websocket`. It applies to all requests to the
ppe this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_websocket
def after():
...
"""
self.record_once(lambda state: state.app.after_websocket(func)) # type: ignore
return func
@setupmethod
def after_app_serving(self, func: T_after_serving) -> 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 :meth:`~quart.Quart.after_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_serving
def after():
...
"""
self.record_once(lambda state: state.app.after_serving(func)) # type: ignore[attr-defined]
return func
@setupmethod
def while_app_serving(self, func: T_while_serving) -> 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 :meth:`~quart.Quart.while_serving`. An example usage,
.. code-block:: python
@blueprint.while_serving
async def func():
... # Startup
yield
... # Shutdown
"""
self.record_once(lambda state: state.app.while_serving(func)) # type: ignore[attr-defined]
return func
@setupmethod
def teardown_app_websocket(self, func: T_teardown) -> 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 :meth:`~quart.Quart.teardown_websocket`. It applies
to all requests to the app this blueprint is registered on. An
example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.teardown_app_websocket
def teardown():
...
"""
self.record_once(lambda state: state.app.teardown_websocket(func)) # type: ignore
return func
def _merge_blueprint_funcs(self, app: App, name: str) -> None:
super()._merge_blueprint_funcs(app, name)
def extend(bp_dict: dict, parent_dict: dict) -> None:
for key, values in bp_dict.items():
key = name if key is None else f"{name}.{key}"
parent_dict[key].extend(values)
for key, value in self.error_handler_spec.items():
key = name if key is None else f"{name}.{key}"
value = defaultdict(
dict,
{
code: {exc_class: func for exc_class, func in code_values.items()}
for code, code_values in value.items()
},
)
app.error_handler_spec[key] = value
extend(self.before_websocket_funcs, app.before_websocket_funcs) # type: ignore
extend(self.after_websocket_funcs, app.after_websocket_funcs) # type: ignore
| (*args: 't.Any', **kwargs: 't.Any') -> 'None' |
29,214 | quart.blueprints | __init__ | null | def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
super().__init__(*args, **kwargs)
self.cli = AppGroup()
self.cli.name = self.name
self.after_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[AfterWebsocketCallable]] = (
defaultdict(list)
)
self.before_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[BeforeWebsocketCallable]] = (
defaultdict(list)
)
self.teardown_websocket_funcs: dict[AppOrBlueprintKey, list[TeardownCallable]] = (
defaultdict(list)
)
| (self, *args: Any, **kwargs: Any) -> NoneType |
29,218 | quart.blueprints | _merge_blueprint_funcs | null | def _merge_blueprint_funcs(self, app: App, name: str) -> None:
super()._merge_blueprint_funcs(app, name)
def extend(bp_dict: dict, parent_dict: dict) -> None:
for key, values in bp_dict.items():
key = name if key is None else f"{name}.{key}"
parent_dict[key].extend(values)
for key, value in self.error_handler_spec.items():
key = name if key is None else f"{name}.{key}"
value = defaultdict(
dict,
{
code: {exc_class: func for exc_class, func in code_values.items()}
for code, code_values in value.items()
},
)
app.error_handler_spec[key] = value
extend(self.before_websocket_funcs, app.before_websocket_funcs) # type: ignore
extend(self.after_websocket_funcs, app.after_websocket_funcs) # type: ignore
| (self, app: flask.sansio.app.App, name: str) -> NoneType |
29,224 | quart.blueprints | add_websocket | Add a websocket url rule to the application.
This is designed to be used on the application directly. An
example usage,
.. code-block:: python
def websocket_route():
...
app.add_websocket('/', websocket_route)
Arguments:
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``,
.. code-block:: python
@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).
| def add_websocket(
self,
rule: str,
endpoint: str | None = None,
view_func: WebsocketCallable | None = None,
**options: t.Any,
) -> None:
"""Add a websocket url rule to the application.
This is designed to be used on the application directly. An
example usage,
.. code-block:: python
def websocket_route():
...
app.add_websocket('/', websocket_route)
Arguments:
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``,
.. code-block:: python
@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).
"""
return self.add_url_rule(
rule,
endpoint,
view_func,
methods={"GET"},
websocket=True,
**options,
)
| (self, rule: 'str', endpoint: 'str | None' = None, view_func: 'WebsocketCallable | None' = None, **options: 't.Any') -> 'None' |
29,226 | quart.blueprints | after_app_serving | Add an after serving function to the App.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.after_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_serving
def after():
...
| from __future__ import annotations
import os
import typing as t
from collections import defaultdict
from datetime import timedelta
from aiofiles import open as async_open
from aiofiles.base import AiofilesContextManager
from aiofiles.threadpool.binary import AsyncBufferedReader
from flask.sansio.app import App
from flask.sansio.blueprints import ( # noqa
Blueprint as SansioBlueprint,
BlueprintSetupState as BlueprintSetupState,
)
from flask.sansio.scaffold import setupmethod
from .cli import AppGroup
from .globals import current_app
from .helpers import send_from_directory
from .typing import (
AfterServingCallable,
AfterWebsocketCallable,
AppOrBlueprintKey,
BeforeServingCallable,
BeforeWebsocketCallable,
FilePath,
TeardownCallable,
WebsocketCallable,
WhileServingCallable,
)
if t.TYPE_CHECKING:
from .wrappers import Response
T_after_serving = t.TypeVar("T_after_serving", bound=AfterServingCallable)
T_after_websocket = t.TypeVar("T_after_websocket", bound=AfterWebsocketCallable)
T_before_serving = t.TypeVar("T_before_serving", bound=BeforeServingCallable)
T_before_websocket = t.TypeVar("T_before_websocket", bound=BeforeWebsocketCallable)
T_teardown = t.TypeVar("T_teardown", bound=TeardownCallable)
T_websocket = t.TypeVar("T_websocket", bound=WebsocketCallable)
T_while_serving = t.TypeVar("T_while_serving", bound=WhileServingCallable)
class Blueprint(SansioBlueprint):
"""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.
"""
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
super().__init__(*args, **kwargs)
self.cli = AppGroup()
self.cli.name = self.name
self.after_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[AfterWebsocketCallable]] = (
defaultdict(list)
)
self.before_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[BeforeWebsocketCallable]] = (
defaultdict(list)
)
self.teardown_websocket_funcs: dict[AppOrBlueprintKey, list[TeardownCallable]] = (
defaultdict(list)
)
def get_send_file_max_age(self, filename: str | None) -> int | None:
"""Used by :func:`send_file` to determine the ``max_age`` cache
value for a given file path if it wasn't passed.
By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
the configuration of :data:`~flask.current_app`. This defaults
to ``None``, which tells the browser to use conditional requests
instead of a timed cache, which is usually preferable.
Note this is a duplicate of the same method in the Quart
class.
"""
value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]
if value is None:
return None
if isinstance(value, timedelta):
return int(value.total_seconds())
return value
return None
async def send_static_file(self, filename: str) -> Response:
if not self.has_static_folder:
raise RuntimeError("No static folder for this object")
return await send_from_directory(self.static_folder, filename)
async def open_resource(
self,
path: FilePath,
mode: str = "rb",
) -> AiofilesContextManager[None, None, AsyncBufferedReader]:
"""Open a file for reading.
Use as
.. code-block:: python
async with await app.open_resource(path) as file_:
await file_.read()
"""
if mode not in {"r", "rb", "rt"}:
raise ValueError("Files can only be opened for reading")
return async_open(os.path.join(self.root_path, path), mode) # type: ignore
def websocket(
self,
rule: str,
**options: t.Any,
) -> t.Callable[[T_websocket], T_websocket]:
"""Add a websocket to the application.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.websocket('/')
async def websocket_route():
...
Arguments:
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``,
.. code-block:: python
@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).
"""
def decorator(func: T_websocket) -> T_websocket:
endpoint = options.pop("endpoint", None)
self.add_websocket(
rule,
endpoint,
func,
**options,
)
return func
return decorator
def add_websocket(
self,
rule: str,
endpoint: str | None = None,
view_func: WebsocketCallable | None = None,
**options: t.Any,
) -> None:
"""Add a websocket url rule to the application.
This is designed to be used on the application directly. An
example usage,
.. code-block:: python
def websocket_route():
...
app.add_websocket('/', websocket_route)
Arguments:
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``,
.. code-block:: python
@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).
"""
return self.add_url_rule(
rule,
endpoint,
view_func,
methods={"GET"},
websocket=True,
**options,
)
@setupmethod
def before_websocket(
self,
func: T_before_websocket,
) -> T_before_websocket:
"""Add a before websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.before_websocket
async def func():
...
Arguments:
func: The before websocket function itself.
"""
self.before_websocket_funcs[None].append(func)
return func
@setupmethod
def after_websocket(
self,
func: T_after_websocket,
) -> T_after_websocket:
"""Add an after websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.after_websocket
async def func(response):
return response
Arguments:
func: The after websocket function itself.
"""
self.after_websocket_funcs[None].append(func)
return func
@setupmethod
def teardown_websocket(
self,
func: T_teardown,
) -> T_teardown:
"""Add a teardown websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.teardown_websocket
async def func():
...
Arguments:
func: The teardown websocket function itself.
name: Optional blueprint key name.
"""
self.teardown_websocket_funcs[None].append(func)
return func
@setupmethod
def before_app_websocket(self, func: T_before_websocket) -> 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 :meth:`~quart.Quart.before_websocket`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_websocket
def before():
...
"""
self.record_once(lambda state: state.app.before_websocket(func)) # type: ignore
return func
@setupmethod
def before_app_serving(self, func: T_before_serving) -> 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 :meth:`~quart.Quart.before_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_serving
def before():
...
"""
self.record_once(lambda state: state.app.before_serving(func)) # type: ignore
return func
@setupmethod
def after_app_websocket(self, func: T_after_websocket) -> 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 :meth:`~quart.Quart.after_websocket`. It applies to all requests to the
ppe this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_websocket
def after():
...
"""
self.record_once(lambda state: state.app.after_websocket(func)) # type: ignore
return func
@setupmethod
def after_app_serving(self, func: T_after_serving) -> 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 :meth:`~quart.Quart.after_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_serving
def after():
...
"""
self.record_once(lambda state: state.app.after_serving(func)) # type: ignore[attr-defined]
return func
@setupmethod
def while_app_serving(self, func: T_while_serving) -> 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 :meth:`~quart.Quart.while_serving`. An example usage,
.. code-block:: python
@blueprint.while_serving
async def func():
... # Startup
yield
... # Shutdown
"""
self.record_once(lambda state: state.app.while_serving(func)) # type: ignore[attr-defined]
return func
@setupmethod
def teardown_app_websocket(self, func: T_teardown) -> 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 :meth:`~quart.Quart.teardown_websocket`. It applies
to all requests to the app this blueprint is registered on. An
example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.teardown_app_websocket
def teardown():
...
"""
self.record_once(lambda state: state.app.teardown_websocket(func)) # type: ignore
return func
def _merge_blueprint_funcs(self, app: App, name: str) -> None:
super()._merge_blueprint_funcs(app, name)
def extend(bp_dict: dict, parent_dict: dict) -> None:
for key, values in bp_dict.items():
key = name if key is None else f"{name}.{key}"
parent_dict[key].extend(values)
for key, value in self.error_handler_spec.items():
key = name if key is None else f"{name}.{key}"
value = defaultdict(
dict,
{
code: {exc_class: func for exc_class, func in code_values.items()}
for code, code_values in value.items()
},
)
app.error_handler_spec[key] = value
extend(self.before_websocket_funcs, app.before_websocket_funcs) # type: ignore
extend(self.after_websocket_funcs, app.after_websocket_funcs) # type: ignore
| (self, func: ~T_after_serving) -> ~T_after_serving |
29,227 | quart.blueprints | after_app_websocket | Add an after websocket function to the App.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.after_websocket`. It applies to all requests to the
ppe this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_websocket
def after():
...
| from __future__ import annotations
import os
import typing as t
from collections import defaultdict
from datetime import timedelta
from aiofiles import open as async_open
from aiofiles.base import AiofilesContextManager
from aiofiles.threadpool.binary import AsyncBufferedReader
from flask.sansio.app import App
from flask.sansio.blueprints import ( # noqa
Blueprint as SansioBlueprint,
BlueprintSetupState as BlueprintSetupState,
)
from flask.sansio.scaffold import setupmethod
from .cli import AppGroup
from .globals import current_app
from .helpers import send_from_directory
from .typing import (
AfterServingCallable,
AfterWebsocketCallable,
AppOrBlueprintKey,
BeforeServingCallable,
BeforeWebsocketCallable,
FilePath,
TeardownCallable,
WebsocketCallable,
WhileServingCallable,
)
if t.TYPE_CHECKING:
from .wrappers import Response
T_after_serving = t.TypeVar("T_after_serving", bound=AfterServingCallable)
T_after_websocket = t.TypeVar("T_after_websocket", bound=AfterWebsocketCallable)
T_before_serving = t.TypeVar("T_before_serving", bound=BeforeServingCallable)
T_before_websocket = t.TypeVar("T_before_websocket", bound=BeforeWebsocketCallable)
T_teardown = t.TypeVar("T_teardown", bound=TeardownCallable)
T_websocket = t.TypeVar("T_websocket", bound=WebsocketCallable)
T_while_serving = t.TypeVar("T_while_serving", bound=WhileServingCallable)
class Blueprint(SansioBlueprint):
"""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.
"""
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
super().__init__(*args, **kwargs)
self.cli = AppGroup()
self.cli.name = self.name
self.after_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[AfterWebsocketCallable]] = (
defaultdict(list)
)
self.before_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[BeforeWebsocketCallable]] = (
defaultdict(list)
)
self.teardown_websocket_funcs: dict[AppOrBlueprintKey, list[TeardownCallable]] = (
defaultdict(list)
)
def get_send_file_max_age(self, filename: str | None) -> int | None:
"""Used by :func:`send_file` to determine the ``max_age`` cache
value for a given file path if it wasn't passed.
By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
the configuration of :data:`~flask.current_app`. This defaults
to ``None``, which tells the browser to use conditional requests
instead of a timed cache, which is usually preferable.
Note this is a duplicate of the same method in the Quart
class.
"""
value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]
if value is None:
return None
if isinstance(value, timedelta):
return int(value.total_seconds())
return value
return None
async def send_static_file(self, filename: str) -> Response:
if not self.has_static_folder:
raise RuntimeError("No static folder for this object")
return await send_from_directory(self.static_folder, filename)
async def open_resource(
self,
path: FilePath,
mode: str = "rb",
) -> AiofilesContextManager[None, None, AsyncBufferedReader]:
"""Open a file for reading.
Use as
.. code-block:: python
async with await app.open_resource(path) as file_:
await file_.read()
"""
if mode not in {"r", "rb", "rt"}:
raise ValueError("Files can only be opened for reading")
return async_open(os.path.join(self.root_path, path), mode) # type: ignore
def websocket(
self,
rule: str,
**options: t.Any,
) -> t.Callable[[T_websocket], T_websocket]:
"""Add a websocket to the application.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.websocket('/')
async def websocket_route():
...
Arguments:
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``,
.. code-block:: python
@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).
"""
def decorator(func: T_websocket) -> T_websocket:
endpoint = options.pop("endpoint", None)
self.add_websocket(
rule,
endpoint,
func,
**options,
)
return func
return decorator
def add_websocket(
self,
rule: str,
endpoint: str | None = None,
view_func: WebsocketCallable | None = None,
**options: t.Any,
) -> None:
"""Add a websocket url rule to the application.
This is designed to be used on the application directly. An
example usage,
.. code-block:: python
def websocket_route():
...
app.add_websocket('/', websocket_route)
Arguments:
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``,
.. code-block:: python
@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).
"""
return self.add_url_rule(
rule,
endpoint,
view_func,
methods={"GET"},
websocket=True,
**options,
)
@setupmethod
def before_websocket(
self,
func: T_before_websocket,
) -> T_before_websocket:
"""Add a before websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.before_websocket
async def func():
...
Arguments:
func: The before websocket function itself.
"""
self.before_websocket_funcs[None].append(func)
return func
@setupmethod
def after_websocket(
self,
func: T_after_websocket,
) -> T_after_websocket:
"""Add an after websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.after_websocket
async def func(response):
return response
Arguments:
func: The after websocket function itself.
"""
self.after_websocket_funcs[None].append(func)
return func
@setupmethod
def teardown_websocket(
self,
func: T_teardown,
) -> T_teardown:
"""Add a teardown websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.teardown_websocket
async def func():
...
Arguments:
func: The teardown websocket function itself.
name: Optional blueprint key name.
"""
self.teardown_websocket_funcs[None].append(func)
return func
@setupmethod
def before_app_websocket(self, func: T_before_websocket) -> 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 :meth:`~quart.Quart.before_websocket`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_websocket
def before():
...
"""
self.record_once(lambda state: state.app.before_websocket(func)) # type: ignore
return func
@setupmethod
def before_app_serving(self, func: T_before_serving) -> 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 :meth:`~quart.Quart.before_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_serving
def before():
...
"""
self.record_once(lambda state: state.app.before_serving(func)) # type: ignore
return func
@setupmethod
def after_app_websocket(self, func: T_after_websocket) -> 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 :meth:`~quart.Quart.after_websocket`. It applies to all requests to the
ppe this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_websocket
def after():
...
"""
self.record_once(lambda state: state.app.after_websocket(func)) # type: ignore
return func
@setupmethod
def after_app_serving(self, func: T_after_serving) -> 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 :meth:`~quart.Quart.after_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_serving
def after():
...
"""
self.record_once(lambda state: state.app.after_serving(func)) # type: ignore[attr-defined]
return func
@setupmethod
def while_app_serving(self, func: T_while_serving) -> 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 :meth:`~quart.Quart.while_serving`. An example usage,
.. code-block:: python
@blueprint.while_serving
async def func():
... # Startup
yield
... # Shutdown
"""
self.record_once(lambda state: state.app.while_serving(func)) # type: ignore[attr-defined]
return func
@setupmethod
def teardown_app_websocket(self, func: T_teardown) -> 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 :meth:`~quart.Quart.teardown_websocket`. It applies
to all requests to the app this blueprint is registered on. An
example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.teardown_app_websocket
def teardown():
...
"""
self.record_once(lambda state: state.app.teardown_websocket(func)) # type: ignore
return func
def _merge_blueprint_funcs(self, app: App, name: str) -> None:
super()._merge_blueprint_funcs(app, name)
def extend(bp_dict: dict, parent_dict: dict) -> None:
for key, values in bp_dict.items():
key = name if key is None else f"{name}.{key}"
parent_dict[key].extend(values)
for key, value in self.error_handler_spec.items():
key = name if key is None else f"{name}.{key}"
value = defaultdict(
dict,
{
code: {exc_class: func for exc_class, func in code_values.items()}
for code, code_values in value.items()
},
)
app.error_handler_spec[key] = value
extend(self.before_websocket_funcs, app.before_websocket_funcs) # type: ignore
extend(self.after_websocket_funcs, app.after_websocket_funcs) # type: ignore
| (self, func: ~T_after_websocket) -> ~T_after_websocket |
29,229 | quart.blueprints | after_websocket | Add an after websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.after_websocket
async def func(response):
return response
Arguments:
func: The after websocket function itself.
| from __future__ import annotations
import os
import typing as t
from collections import defaultdict
from datetime import timedelta
from aiofiles import open as async_open
from aiofiles.base import AiofilesContextManager
from aiofiles.threadpool.binary import AsyncBufferedReader
from flask.sansio.app import App
from flask.sansio.blueprints import ( # noqa
Blueprint as SansioBlueprint,
BlueprintSetupState as BlueprintSetupState,
)
from flask.sansio.scaffold import setupmethod
from .cli import AppGroup
from .globals import current_app
from .helpers import send_from_directory
from .typing import (
AfterServingCallable,
AfterWebsocketCallable,
AppOrBlueprintKey,
BeforeServingCallable,
BeforeWebsocketCallable,
FilePath,
TeardownCallable,
WebsocketCallable,
WhileServingCallable,
)
if t.TYPE_CHECKING:
from .wrappers import Response
T_after_serving = t.TypeVar("T_after_serving", bound=AfterServingCallable)
T_after_websocket = t.TypeVar("T_after_websocket", bound=AfterWebsocketCallable)
T_before_serving = t.TypeVar("T_before_serving", bound=BeforeServingCallable)
T_before_websocket = t.TypeVar("T_before_websocket", bound=BeforeWebsocketCallable)
T_teardown = t.TypeVar("T_teardown", bound=TeardownCallable)
T_websocket = t.TypeVar("T_websocket", bound=WebsocketCallable)
T_while_serving = t.TypeVar("T_while_serving", bound=WhileServingCallable)
class Blueprint(SansioBlueprint):
"""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.
"""
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
super().__init__(*args, **kwargs)
self.cli = AppGroup()
self.cli.name = self.name
self.after_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[AfterWebsocketCallable]] = (
defaultdict(list)
)
self.before_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[BeforeWebsocketCallable]] = (
defaultdict(list)
)
self.teardown_websocket_funcs: dict[AppOrBlueprintKey, list[TeardownCallable]] = (
defaultdict(list)
)
def get_send_file_max_age(self, filename: str | None) -> int | None:
"""Used by :func:`send_file` to determine the ``max_age`` cache
value for a given file path if it wasn't passed.
By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
the configuration of :data:`~flask.current_app`. This defaults
to ``None``, which tells the browser to use conditional requests
instead of a timed cache, which is usually preferable.
Note this is a duplicate of the same method in the Quart
class.
"""
value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]
if value is None:
return None
if isinstance(value, timedelta):
return int(value.total_seconds())
return value
return None
async def send_static_file(self, filename: str) -> Response:
if not self.has_static_folder:
raise RuntimeError("No static folder for this object")
return await send_from_directory(self.static_folder, filename)
async def open_resource(
self,
path: FilePath,
mode: str = "rb",
) -> AiofilesContextManager[None, None, AsyncBufferedReader]:
"""Open a file for reading.
Use as
.. code-block:: python
async with await app.open_resource(path) as file_:
await file_.read()
"""
if mode not in {"r", "rb", "rt"}:
raise ValueError("Files can only be opened for reading")
return async_open(os.path.join(self.root_path, path), mode) # type: ignore
def websocket(
self,
rule: str,
**options: t.Any,
) -> t.Callable[[T_websocket], T_websocket]:
"""Add a websocket to the application.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.websocket('/')
async def websocket_route():
...
Arguments:
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``,
.. code-block:: python
@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).
"""
def decorator(func: T_websocket) -> T_websocket:
endpoint = options.pop("endpoint", None)
self.add_websocket(
rule,
endpoint,
func,
**options,
)
return func
return decorator
def add_websocket(
self,
rule: str,
endpoint: str | None = None,
view_func: WebsocketCallable | None = None,
**options: t.Any,
) -> None:
"""Add a websocket url rule to the application.
This is designed to be used on the application directly. An
example usage,
.. code-block:: python
def websocket_route():
...
app.add_websocket('/', websocket_route)
Arguments:
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``,
.. code-block:: python
@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).
"""
return self.add_url_rule(
rule,
endpoint,
view_func,
methods={"GET"},
websocket=True,
**options,
)
@setupmethod
def before_websocket(
self,
func: T_before_websocket,
) -> T_before_websocket:
"""Add a before websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.before_websocket
async def func():
...
Arguments:
func: The before websocket function itself.
"""
self.before_websocket_funcs[None].append(func)
return func
@setupmethod
def after_websocket(
self,
func: T_after_websocket,
) -> T_after_websocket:
"""Add an after websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.after_websocket
async def func(response):
return response
Arguments:
func: The after websocket function itself.
"""
self.after_websocket_funcs[None].append(func)
return func
@setupmethod
def teardown_websocket(
self,
func: T_teardown,
) -> T_teardown:
"""Add a teardown websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.teardown_websocket
async def func():
...
Arguments:
func: The teardown websocket function itself.
name: Optional blueprint key name.
"""
self.teardown_websocket_funcs[None].append(func)
return func
@setupmethod
def before_app_websocket(self, func: T_before_websocket) -> 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 :meth:`~quart.Quart.before_websocket`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_websocket
def before():
...
"""
self.record_once(lambda state: state.app.before_websocket(func)) # type: ignore
return func
@setupmethod
def before_app_serving(self, func: T_before_serving) -> 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 :meth:`~quart.Quart.before_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_serving
def before():
...
"""
self.record_once(lambda state: state.app.before_serving(func)) # type: ignore
return func
@setupmethod
def after_app_websocket(self, func: T_after_websocket) -> 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 :meth:`~quart.Quart.after_websocket`. It applies to all requests to the
ppe this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_websocket
def after():
...
"""
self.record_once(lambda state: state.app.after_websocket(func)) # type: ignore
return func
@setupmethod
def after_app_serving(self, func: T_after_serving) -> 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 :meth:`~quart.Quart.after_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_serving
def after():
...
"""
self.record_once(lambda state: state.app.after_serving(func)) # type: ignore[attr-defined]
return func
@setupmethod
def while_app_serving(self, func: T_while_serving) -> 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 :meth:`~quart.Quart.while_serving`. An example usage,
.. code-block:: python
@blueprint.while_serving
async def func():
... # Startup
yield
... # Shutdown
"""
self.record_once(lambda state: state.app.while_serving(func)) # type: ignore[attr-defined]
return func
@setupmethod
def teardown_app_websocket(self, func: T_teardown) -> 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 :meth:`~quart.Quart.teardown_websocket`. It applies
to all requests to the app this blueprint is registered on. An
example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.teardown_app_websocket
def teardown():
...
"""
self.record_once(lambda state: state.app.teardown_websocket(func)) # type: ignore
return func
def _merge_blueprint_funcs(self, app: App, name: str) -> None:
super()._merge_blueprint_funcs(app, name)
def extend(bp_dict: dict, parent_dict: dict) -> None:
for key, values in bp_dict.items():
key = name if key is None else f"{name}.{key}"
parent_dict[key].extend(values)
for key, value in self.error_handler_spec.items():
key = name if key is None else f"{name}.{key}"
value = defaultdict(
dict,
{
code: {exc_class: func for exc_class, func in code_values.items()}
for code, code_values in value.items()
},
)
app.error_handler_spec[key] = value
extend(self.before_websocket_funcs, app.before_websocket_funcs) # type: ignore
extend(self.after_websocket_funcs, app.after_websocket_funcs) # type: ignore
| (self, func: ~T_after_websocket) -> ~T_after_websocket |
29,238 | quart.blueprints | before_app_serving | Add a before serving to the App.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.before_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_serving
def before():
...
| from __future__ import annotations
import os
import typing as t
from collections import defaultdict
from datetime import timedelta
from aiofiles import open as async_open
from aiofiles.base import AiofilesContextManager
from aiofiles.threadpool.binary import AsyncBufferedReader
from flask.sansio.app import App
from flask.sansio.blueprints import ( # noqa
Blueprint as SansioBlueprint,
BlueprintSetupState as BlueprintSetupState,
)
from flask.sansio.scaffold import setupmethod
from .cli import AppGroup
from .globals import current_app
from .helpers import send_from_directory
from .typing import (
AfterServingCallable,
AfterWebsocketCallable,
AppOrBlueprintKey,
BeforeServingCallable,
BeforeWebsocketCallable,
FilePath,
TeardownCallable,
WebsocketCallable,
WhileServingCallable,
)
if t.TYPE_CHECKING:
from .wrappers import Response
T_after_serving = t.TypeVar("T_after_serving", bound=AfterServingCallable)
T_after_websocket = t.TypeVar("T_after_websocket", bound=AfterWebsocketCallable)
T_before_serving = t.TypeVar("T_before_serving", bound=BeforeServingCallable)
T_before_websocket = t.TypeVar("T_before_websocket", bound=BeforeWebsocketCallable)
T_teardown = t.TypeVar("T_teardown", bound=TeardownCallable)
T_websocket = t.TypeVar("T_websocket", bound=WebsocketCallable)
T_while_serving = t.TypeVar("T_while_serving", bound=WhileServingCallable)
class Blueprint(SansioBlueprint):
"""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.
"""
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
super().__init__(*args, **kwargs)
self.cli = AppGroup()
self.cli.name = self.name
self.after_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[AfterWebsocketCallable]] = (
defaultdict(list)
)
self.before_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[BeforeWebsocketCallable]] = (
defaultdict(list)
)
self.teardown_websocket_funcs: dict[AppOrBlueprintKey, list[TeardownCallable]] = (
defaultdict(list)
)
def get_send_file_max_age(self, filename: str | None) -> int | None:
"""Used by :func:`send_file` to determine the ``max_age`` cache
value for a given file path if it wasn't passed.
By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
the configuration of :data:`~flask.current_app`. This defaults
to ``None``, which tells the browser to use conditional requests
instead of a timed cache, which is usually preferable.
Note this is a duplicate of the same method in the Quart
class.
"""
value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]
if value is None:
return None
if isinstance(value, timedelta):
return int(value.total_seconds())
return value
return None
async def send_static_file(self, filename: str) -> Response:
if not self.has_static_folder:
raise RuntimeError("No static folder for this object")
return await send_from_directory(self.static_folder, filename)
async def open_resource(
self,
path: FilePath,
mode: str = "rb",
) -> AiofilesContextManager[None, None, AsyncBufferedReader]:
"""Open a file for reading.
Use as
.. code-block:: python
async with await app.open_resource(path) as file_:
await file_.read()
"""
if mode not in {"r", "rb", "rt"}:
raise ValueError("Files can only be opened for reading")
return async_open(os.path.join(self.root_path, path), mode) # type: ignore
def websocket(
self,
rule: str,
**options: t.Any,
) -> t.Callable[[T_websocket], T_websocket]:
"""Add a websocket to the application.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.websocket('/')
async def websocket_route():
...
Arguments:
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``,
.. code-block:: python
@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).
"""
def decorator(func: T_websocket) -> T_websocket:
endpoint = options.pop("endpoint", None)
self.add_websocket(
rule,
endpoint,
func,
**options,
)
return func
return decorator
def add_websocket(
self,
rule: str,
endpoint: str | None = None,
view_func: WebsocketCallable | None = None,
**options: t.Any,
) -> None:
"""Add a websocket url rule to the application.
This is designed to be used on the application directly. An
example usage,
.. code-block:: python
def websocket_route():
...
app.add_websocket('/', websocket_route)
Arguments:
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``,
.. code-block:: python
@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).
"""
return self.add_url_rule(
rule,
endpoint,
view_func,
methods={"GET"},
websocket=True,
**options,
)
@setupmethod
def before_websocket(
self,
func: T_before_websocket,
) -> T_before_websocket:
"""Add a before websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.before_websocket
async def func():
...
Arguments:
func: The before websocket function itself.
"""
self.before_websocket_funcs[None].append(func)
return func
@setupmethod
def after_websocket(
self,
func: T_after_websocket,
) -> T_after_websocket:
"""Add an after websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.after_websocket
async def func(response):
return response
Arguments:
func: The after websocket function itself.
"""
self.after_websocket_funcs[None].append(func)
return func
@setupmethod
def teardown_websocket(
self,
func: T_teardown,
) -> T_teardown:
"""Add a teardown websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.teardown_websocket
async def func():
...
Arguments:
func: The teardown websocket function itself.
name: Optional blueprint key name.
"""
self.teardown_websocket_funcs[None].append(func)
return func
@setupmethod
def before_app_websocket(self, func: T_before_websocket) -> 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 :meth:`~quart.Quart.before_websocket`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_websocket
def before():
...
"""
self.record_once(lambda state: state.app.before_websocket(func)) # type: ignore
return func
@setupmethod
def before_app_serving(self, func: T_before_serving) -> 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 :meth:`~quart.Quart.before_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_serving
def before():
...
"""
self.record_once(lambda state: state.app.before_serving(func)) # type: ignore
return func
@setupmethod
def after_app_websocket(self, func: T_after_websocket) -> 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 :meth:`~quart.Quart.after_websocket`. It applies to all requests to the
ppe this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_websocket
def after():
...
"""
self.record_once(lambda state: state.app.after_websocket(func)) # type: ignore
return func
@setupmethod
def after_app_serving(self, func: T_after_serving) -> 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 :meth:`~quart.Quart.after_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_serving
def after():
...
"""
self.record_once(lambda state: state.app.after_serving(func)) # type: ignore[attr-defined]
return func
@setupmethod
def while_app_serving(self, func: T_while_serving) -> 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 :meth:`~quart.Quart.while_serving`. An example usage,
.. code-block:: python
@blueprint.while_serving
async def func():
... # Startup
yield
... # Shutdown
"""
self.record_once(lambda state: state.app.while_serving(func)) # type: ignore[attr-defined]
return func
@setupmethod
def teardown_app_websocket(self, func: T_teardown) -> 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 :meth:`~quart.Quart.teardown_websocket`. It applies
to all requests to the app this blueprint is registered on. An
example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.teardown_app_websocket
def teardown():
...
"""
self.record_once(lambda state: state.app.teardown_websocket(func)) # type: ignore
return func
def _merge_blueprint_funcs(self, app: App, name: str) -> None:
super()._merge_blueprint_funcs(app, name)
def extend(bp_dict: dict, parent_dict: dict) -> None:
for key, values in bp_dict.items():
key = name if key is None else f"{name}.{key}"
parent_dict[key].extend(values)
for key, value in self.error_handler_spec.items():
key = name if key is None else f"{name}.{key}"
value = defaultdict(
dict,
{
code: {exc_class: func for exc_class, func in code_values.items()}
for code, code_values in value.items()
},
)
app.error_handler_spec[key] = value
extend(self.before_websocket_funcs, app.before_websocket_funcs) # type: ignore
extend(self.after_websocket_funcs, app.after_websocket_funcs) # type: ignore
| (self, func: ~T_before_serving) -> ~T_before_serving |
29,239 | quart.blueprints | before_app_websocket | Add a before websocket to the App.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.before_websocket`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_websocket
def before():
...
| from __future__ import annotations
import os
import typing as t
from collections import defaultdict
from datetime import timedelta
from aiofiles import open as async_open
from aiofiles.base import AiofilesContextManager
from aiofiles.threadpool.binary import AsyncBufferedReader
from flask.sansio.app import App
from flask.sansio.blueprints import ( # noqa
Blueprint as SansioBlueprint,
BlueprintSetupState as BlueprintSetupState,
)
from flask.sansio.scaffold import setupmethod
from .cli import AppGroup
from .globals import current_app
from .helpers import send_from_directory
from .typing import (
AfterServingCallable,
AfterWebsocketCallable,
AppOrBlueprintKey,
BeforeServingCallable,
BeforeWebsocketCallable,
FilePath,
TeardownCallable,
WebsocketCallable,
WhileServingCallable,
)
if t.TYPE_CHECKING:
from .wrappers import Response
T_after_serving = t.TypeVar("T_after_serving", bound=AfterServingCallable)
T_after_websocket = t.TypeVar("T_after_websocket", bound=AfterWebsocketCallable)
T_before_serving = t.TypeVar("T_before_serving", bound=BeforeServingCallable)
T_before_websocket = t.TypeVar("T_before_websocket", bound=BeforeWebsocketCallable)
T_teardown = t.TypeVar("T_teardown", bound=TeardownCallable)
T_websocket = t.TypeVar("T_websocket", bound=WebsocketCallable)
T_while_serving = t.TypeVar("T_while_serving", bound=WhileServingCallable)
class Blueprint(SansioBlueprint):
"""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.
"""
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
super().__init__(*args, **kwargs)
self.cli = AppGroup()
self.cli.name = self.name
self.after_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[AfterWebsocketCallable]] = (
defaultdict(list)
)
self.before_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[BeforeWebsocketCallable]] = (
defaultdict(list)
)
self.teardown_websocket_funcs: dict[AppOrBlueprintKey, list[TeardownCallable]] = (
defaultdict(list)
)
def get_send_file_max_age(self, filename: str | None) -> int | None:
"""Used by :func:`send_file` to determine the ``max_age`` cache
value for a given file path if it wasn't passed.
By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
the configuration of :data:`~flask.current_app`. This defaults
to ``None``, which tells the browser to use conditional requests
instead of a timed cache, which is usually preferable.
Note this is a duplicate of the same method in the Quart
class.
"""
value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]
if value is None:
return None
if isinstance(value, timedelta):
return int(value.total_seconds())
return value
return None
async def send_static_file(self, filename: str) -> Response:
if not self.has_static_folder:
raise RuntimeError("No static folder for this object")
return await send_from_directory(self.static_folder, filename)
async def open_resource(
self,
path: FilePath,
mode: str = "rb",
) -> AiofilesContextManager[None, None, AsyncBufferedReader]:
"""Open a file for reading.
Use as
.. code-block:: python
async with await app.open_resource(path) as file_:
await file_.read()
"""
if mode not in {"r", "rb", "rt"}:
raise ValueError("Files can only be opened for reading")
return async_open(os.path.join(self.root_path, path), mode) # type: ignore
def websocket(
self,
rule: str,
**options: t.Any,
) -> t.Callable[[T_websocket], T_websocket]:
"""Add a websocket to the application.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.websocket('/')
async def websocket_route():
...
Arguments:
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``,
.. code-block:: python
@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).
"""
def decorator(func: T_websocket) -> T_websocket:
endpoint = options.pop("endpoint", None)
self.add_websocket(
rule,
endpoint,
func,
**options,
)
return func
return decorator
def add_websocket(
self,
rule: str,
endpoint: str | None = None,
view_func: WebsocketCallable | None = None,
**options: t.Any,
) -> None:
"""Add a websocket url rule to the application.
This is designed to be used on the application directly. An
example usage,
.. code-block:: python
def websocket_route():
...
app.add_websocket('/', websocket_route)
Arguments:
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``,
.. code-block:: python
@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).
"""
return self.add_url_rule(
rule,
endpoint,
view_func,
methods={"GET"},
websocket=True,
**options,
)
@setupmethod
def before_websocket(
self,
func: T_before_websocket,
) -> T_before_websocket:
"""Add a before websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.before_websocket
async def func():
...
Arguments:
func: The before websocket function itself.
"""
self.before_websocket_funcs[None].append(func)
return func
@setupmethod
def after_websocket(
self,
func: T_after_websocket,
) -> T_after_websocket:
"""Add an after websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.after_websocket
async def func(response):
return response
Arguments:
func: The after websocket function itself.
"""
self.after_websocket_funcs[None].append(func)
return func
@setupmethod
def teardown_websocket(
self,
func: T_teardown,
) -> T_teardown:
"""Add a teardown websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.teardown_websocket
async def func():
...
Arguments:
func: The teardown websocket function itself.
name: Optional blueprint key name.
"""
self.teardown_websocket_funcs[None].append(func)
return func
@setupmethod
def before_app_websocket(self, func: T_before_websocket) -> 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 :meth:`~quart.Quart.before_websocket`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_websocket
def before():
...
"""
self.record_once(lambda state: state.app.before_websocket(func)) # type: ignore
return func
@setupmethod
def before_app_serving(self, func: T_before_serving) -> 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 :meth:`~quart.Quart.before_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_serving
def before():
...
"""
self.record_once(lambda state: state.app.before_serving(func)) # type: ignore
return func
@setupmethod
def after_app_websocket(self, func: T_after_websocket) -> 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 :meth:`~quart.Quart.after_websocket`. It applies to all requests to the
ppe this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_websocket
def after():
...
"""
self.record_once(lambda state: state.app.after_websocket(func)) # type: ignore
return func
@setupmethod
def after_app_serving(self, func: T_after_serving) -> 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 :meth:`~quart.Quart.after_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_serving
def after():
...
"""
self.record_once(lambda state: state.app.after_serving(func)) # type: ignore[attr-defined]
return func
@setupmethod
def while_app_serving(self, func: T_while_serving) -> 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 :meth:`~quart.Quart.while_serving`. An example usage,
.. code-block:: python
@blueprint.while_serving
async def func():
... # Startup
yield
... # Shutdown
"""
self.record_once(lambda state: state.app.while_serving(func)) # type: ignore[attr-defined]
return func
@setupmethod
def teardown_app_websocket(self, func: T_teardown) -> 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 :meth:`~quart.Quart.teardown_websocket`. It applies
to all requests to the app this blueprint is registered on. An
example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.teardown_app_websocket
def teardown():
...
"""
self.record_once(lambda state: state.app.teardown_websocket(func)) # type: ignore
return func
def _merge_blueprint_funcs(self, app: App, name: str) -> None:
super()._merge_blueprint_funcs(app, name)
def extend(bp_dict: dict, parent_dict: dict) -> None:
for key, values in bp_dict.items():
key = name if key is None else f"{name}.{key}"
parent_dict[key].extend(values)
for key, value in self.error_handler_spec.items():
key = name if key is None else f"{name}.{key}"
value = defaultdict(
dict,
{
code: {exc_class: func for exc_class, func in code_values.items()}
for code, code_values in value.items()
},
)
app.error_handler_spec[key] = value
extend(self.before_websocket_funcs, app.before_websocket_funcs) # type: ignore
extend(self.after_websocket_funcs, app.after_websocket_funcs) # type: ignore
| (self, func: ~T_before_websocket) -> ~T_before_websocket |
29,241 | quart.blueprints | before_websocket | Add a before websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.before_websocket
async def func():
...
Arguments:
func: The before websocket function itself.
| from __future__ import annotations
import os
import typing as t
from collections import defaultdict
from datetime import timedelta
from aiofiles import open as async_open
from aiofiles.base import AiofilesContextManager
from aiofiles.threadpool.binary import AsyncBufferedReader
from flask.sansio.app import App
from flask.sansio.blueprints import ( # noqa
Blueprint as SansioBlueprint,
BlueprintSetupState as BlueprintSetupState,
)
from flask.sansio.scaffold import setupmethod
from .cli import AppGroup
from .globals import current_app
from .helpers import send_from_directory
from .typing import (
AfterServingCallable,
AfterWebsocketCallable,
AppOrBlueprintKey,
BeforeServingCallable,
BeforeWebsocketCallable,
FilePath,
TeardownCallable,
WebsocketCallable,
WhileServingCallable,
)
if t.TYPE_CHECKING:
from .wrappers import Response
T_after_serving = t.TypeVar("T_after_serving", bound=AfterServingCallable)
T_after_websocket = t.TypeVar("T_after_websocket", bound=AfterWebsocketCallable)
T_before_serving = t.TypeVar("T_before_serving", bound=BeforeServingCallable)
T_before_websocket = t.TypeVar("T_before_websocket", bound=BeforeWebsocketCallable)
T_teardown = t.TypeVar("T_teardown", bound=TeardownCallable)
T_websocket = t.TypeVar("T_websocket", bound=WebsocketCallable)
T_while_serving = t.TypeVar("T_while_serving", bound=WhileServingCallable)
class Blueprint(SansioBlueprint):
"""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.
"""
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
super().__init__(*args, **kwargs)
self.cli = AppGroup()
self.cli.name = self.name
self.after_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[AfterWebsocketCallable]] = (
defaultdict(list)
)
self.before_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[BeforeWebsocketCallable]] = (
defaultdict(list)
)
self.teardown_websocket_funcs: dict[AppOrBlueprintKey, list[TeardownCallable]] = (
defaultdict(list)
)
def get_send_file_max_age(self, filename: str | None) -> int | None:
"""Used by :func:`send_file` to determine the ``max_age`` cache
value for a given file path if it wasn't passed.
By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
the configuration of :data:`~flask.current_app`. This defaults
to ``None``, which tells the browser to use conditional requests
instead of a timed cache, which is usually preferable.
Note this is a duplicate of the same method in the Quart
class.
"""
value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]
if value is None:
return None
if isinstance(value, timedelta):
return int(value.total_seconds())
return value
return None
async def send_static_file(self, filename: str) -> Response:
if not self.has_static_folder:
raise RuntimeError("No static folder for this object")
return await send_from_directory(self.static_folder, filename)
async def open_resource(
self,
path: FilePath,
mode: str = "rb",
) -> AiofilesContextManager[None, None, AsyncBufferedReader]:
"""Open a file for reading.
Use as
.. code-block:: python
async with await app.open_resource(path) as file_:
await file_.read()
"""
if mode not in {"r", "rb", "rt"}:
raise ValueError("Files can only be opened for reading")
return async_open(os.path.join(self.root_path, path), mode) # type: ignore
def websocket(
self,
rule: str,
**options: t.Any,
) -> t.Callable[[T_websocket], T_websocket]:
"""Add a websocket to the application.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.websocket('/')
async def websocket_route():
...
Arguments:
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``,
.. code-block:: python
@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).
"""
def decorator(func: T_websocket) -> T_websocket:
endpoint = options.pop("endpoint", None)
self.add_websocket(
rule,
endpoint,
func,
**options,
)
return func
return decorator
def add_websocket(
self,
rule: str,
endpoint: str | None = None,
view_func: WebsocketCallable | None = None,
**options: t.Any,
) -> None:
"""Add a websocket url rule to the application.
This is designed to be used on the application directly. An
example usage,
.. code-block:: python
def websocket_route():
...
app.add_websocket('/', websocket_route)
Arguments:
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``,
.. code-block:: python
@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).
"""
return self.add_url_rule(
rule,
endpoint,
view_func,
methods={"GET"},
websocket=True,
**options,
)
@setupmethod
def before_websocket(
self,
func: T_before_websocket,
) -> T_before_websocket:
"""Add a before websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.before_websocket
async def func():
...
Arguments:
func: The before websocket function itself.
"""
self.before_websocket_funcs[None].append(func)
return func
@setupmethod
def after_websocket(
self,
func: T_after_websocket,
) -> T_after_websocket:
"""Add an after websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.after_websocket
async def func(response):
return response
Arguments:
func: The after websocket function itself.
"""
self.after_websocket_funcs[None].append(func)
return func
@setupmethod
def teardown_websocket(
self,
func: T_teardown,
) -> T_teardown:
"""Add a teardown websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.teardown_websocket
async def func():
...
Arguments:
func: The teardown websocket function itself.
name: Optional blueprint key name.
"""
self.teardown_websocket_funcs[None].append(func)
return func
@setupmethod
def before_app_websocket(self, func: T_before_websocket) -> 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 :meth:`~quart.Quart.before_websocket`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_websocket
def before():
...
"""
self.record_once(lambda state: state.app.before_websocket(func)) # type: ignore
return func
@setupmethod
def before_app_serving(self, func: T_before_serving) -> 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 :meth:`~quart.Quart.before_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_serving
def before():
...
"""
self.record_once(lambda state: state.app.before_serving(func)) # type: ignore
return func
@setupmethod
def after_app_websocket(self, func: T_after_websocket) -> 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 :meth:`~quart.Quart.after_websocket`. It applies to all requests to the
ppe this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_websocket
def after():
...
"""
self.record_once(lambda state: state.app.after_websocket(func)) # type: ignore
return func
@setupmethod
def after_app_serving(self, func: T_after_serving) -> 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 :meth:`~quart.Quart.after_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_serving
def after():
...
"""
self.record_once(lambda state: state.app.after_serving(func)) # type: ignore[attr-defined]
return func
@setupmethod
def while_app_serving(self, func: T_while_serving) -> 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 :meth:`~quart.Quart.while_serving`. An example usage,
.. code-block:: python
@blueprint.while_serving
async def func():
... # Startup
yield
... # Shutdown
"""
self.record_once(lambda state: state.app.while_serving(func)) # type: ignore[attr-defined]
return func
@setupmethod
def teardown_app_websocket(self, func: T_teardown) -> 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 :meth:`~quart.Quart.teardown_websocket`. It applies
to all requests to the app this blueprint is registered on. An
example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.teardown_app_websocket
def teardown():
...
"""
self.record_once(lambda state: state.app.teardown_websocket(func)) # type: ignore
return func
def _merge_blueprint_funcs(self, app: App, name: str) -> None:
super()._merge_blueprint_funcs(app, name)
def extend(bp_dict: dict, parent_dict: dict) -> None:
for key, values in bp_dict.items():
key = name if key is None else f"{name}.{key}"
parent_dict[key].extend(values)
for key, value in self.error_handler_spec.items():
key = name if key is None else f"{name}.{key}"
value = defaultdict(
dict,
{
code: {exc_class: func for exc_class, func in code_values.items()}
for code, code_values in value.items()
},
)
app.error_handler_spec[key] = value
extend(self.before_websocket_funcs, app.before_websocket_funcs) # type: ignore
extend(self.after_websocket_funcs, app.after_websocket_funcs) # type: ignore
| (self, func: ~T_before_websocket) -> ~T_before_websocket |
29,247 | quart.blueprints | get_send_file_max_age | Used by :func:`send_file` to determine the ``max_age`` cache
value for a given file path if it wasn't passed.
By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
the configuration of :data:`~flask.current_app`. This defaults
to ``None``, which tells the browser to use conditional requests
instead of a timed cache, which is usually preferable.
Note this is a duplicate of the same method in the Quart
class.
| def get_send_file_max_age(self, filename: str | None) -> int | None:
"""Used by :func:`send_file` to determine the ``max_age`` cache
value for a given file path if it wasn't passed.
By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
the configuration of :data:`~flask.current_app`. This defaults
to ``None``, which tells the browser to use conditional requests
instead of a timed cache, which is usually preferable.
Note this is a duplicate of the same method in the Quart
class.
"""
value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]
if value is None:
return None
if isinstance(value, timedelta):
return int(value.total_seconds())
return value
return None
| (self, filename: str | None) -> int | None |
29,249 | quart.blueprints | open_resource | Open a file for reading.
Use as
.. code-block:: python
async with await app.open_resource(path) as file_:
await file_.read()
| def get_send_file_max_age(self, filename: str | None) -> int | None:
"""Used by :func:`send_file` to determine the ``max_age`` cache
value for a given file path if it wasn't passed.
By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
the configuration of :data:`~flask.current_app`. This defaults
to ``None``, which tells the browser to use conditional requests
instead of a timed cache, which is usually preferable.
Note this is a duplicate of the same method in the Quart
class.
"""
value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]
if value is None:
return None
if isinstance(value, timedelta):
return int(value.total_seconds())
return value
return None
| (self, path: Union[bytes, str, os.PathLike], mode: str = 'rb') -> aiofiles.base.AiofilesContextManager[None, None, aiofiles.threadpool.binary.AsyncBufferedReader] |
29,259 | quart.blueprints | send_static_file | null | def get_send_file_max_age(self, filename: str | None) -> int | None:
"""Used by :func:`send_file` to determine the ``max_age`` cache
value for a given file path if it wasn't passed.
By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
the configuration of :data:`~flask.current_app`. This defaults
to ``None``, which tells the browser to use conditional requests
instead of a timed cache, which is usually preferable.
Note this is a duplicate of the same method in the Quart
class.
"""
value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]
if value is None:
return None
if isinstance(value, timedelta):
return int(value.total_seconds())
return value
return None
| (self, filename: 'str') -> 'Response' |
29,261 | quart.blueprints | teardown_app_websocket | Add a teardown websocket function to the app.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.teardown_websocket`. It applies
to all requests to the app this blueprint is registered on. An
example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.teardown_app_websocket
def teardown():
...
| from __future__ import annotations
import os
import typing as t
from collections import defaultdict
from datetime import timedelta
from aiofiles import open as async_open
from aiofiles.base import AiofilesContextManager
from aiofiles.threadpool.binary import AsyncBufferedReader
from flask.sansio.app import App
from flask.sansio.blueprints import ( # noqa
Blueprint as SansioBlueprint,
BlueprintSetupState as BlueprintSetupState,
)
from flask.sansio.scaffold import setupmethod
from .cli import AppGroup
from .globals import current_app
from .helpers import send_from_directory
from .typing import (
AfterServingCallable,
AfterWebsocketCallable,
AppOrBlueprintKey,
BeforeServingCallable,
BeforeWebsocketCallable,
FilePath,
TeardownCallable,
WebsocketCallable,
WhileServingCallable,
)
if t.TYPE_CHECKING:
from .wrappers import Response
T_after_serving = t.TypeVar("T_after_serving", bound=AfterServingCallable)
T_after_websocket = t.TypeVar("T_after_websocket", bound=AfterWebsocketCallable)
T_before_serving = t.TypeVar("T_before_serving", bound=BeforeServingCallable)
T_before_websocket = t.TypeVar("T_before_websocket", bound=BeforeWebsocketCallable)
T_teardown = t.TypeVar("T_teardown", bound=TeardownCallable)
T_websocket = t.TypeVar("T_websocket", bound=WebsocketCallable)
T_while_serving = t.TypeVar("T_while_serving", bound=WhileServingCallable)
class Blueprint(SansioBlueprint):
"""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.
"""
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
super().__init__(*args, **kwargs)
self.cli = AppGroup()
self.cli.name = self.name
self.after_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[AfterWebsocketCallable]] = (
defaultdict(list)
)
self.before_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[BeforeWebsocketCallable]] = (
defaultdict(list)
)
self.teardown_websocket_funcs: dict[AppOrBlueprintKey, list[TeardownCallable]] = (
defaultdict(list)
)
def get_send_file_max_age(self, filename: str | None) -> int | None:
"""Used by :func:`send_file` to determine the ``max_age`` cache
value for a given file path if it wasn't passed.
By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
the configuration of :data:`~flask.current_app`. This defaults
to ``None``, which tells the browser to use conditional requests
instead of a timed cache, which is usually preferable.
Note this is a duplicate of the same method in the Quart
class.
"""
value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]
if value is None:
return None
if isinstance(value, timedelta):
return int(value.total_seconds())
return value
return None
async def send_static_file(self, filename: str) -> Response:
if not self.has_static_folder:
raise RuntimeError("No static folder for this object")
return await send_from_directory(self.static_folder, filename)
async def open_resource(
self,
path: FilePath,
mode: str = "rb",
) -> AiofilesContextManager[None, None, AsyncBufferedReader]:
"""Open a file for reading.
Use as
.. code-block:: python
async with await app.open_resource(path) as file_:
await file_.read()
"""
if mode not in {"r", "rb", "rt"}:
raise ValueError("Files can only be opened for reading")
return async_open(os.path.join(self.root_path, path), mode) # type: ignore
def websocket(
self,
rule: str,
**options: t.Any,
) -> t.Callable[[T_websocket], T_websocket]:
"""Add a websocket to the application.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.websocket('/')
async def websocket_route():
...
Arguments:
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``,
.. code-block:: python
@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).
"""
def decorator(func: T_websocket) -> T_websocket:
endpoint = options.pop("endpoint", None)
self.add_websocket(
rule,
endpoint,
func,
**options,
)
return func
return decorator
def add_websocket(
self,
rule: str,
endpoint: str | None = None,
view_func: WebsocketCallable | None = None,
**options: t.Any,
) -> None:
"""Add a websocket url rule to the application.
This is designed to be used on the application directly. An
example usage,
.. code-block:: python
def websocket_route():
...
app.add_websocket('/', websocket_route)
Arguments:
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``,
.. code-block:: python
@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).
"""
return self.add_url_rule(
rule,
endpoint,
view_func,
methods={"GET"},
websocket=True,
**options,
)
@setupmethod
def before_websocket(
self,
func: T_before_websocket,
) -> T_before_websocket:
"""Add a before websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.before_websocket
async def func():
...
Arguments:
func: The before websocket function itself.
"""
self.before_websocket_funcs[None].append(func)
return func
@setupmethod
def after_websocket(
self,
func: T_after_websocket,
) -> T_after_websocket:
"""Add an after websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.after_websocket
async def func(response):
return response
Arguments:
func: The after websocket function itself.
"""
self.after_websocket_funcs[None].append(func)
return func
@setupmethod
def teardown_websocket(
self,
func: T_teardown,
) -> T_teardown:
"""Add a teardown websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.teardown_websocket
async def func():
...
Arguments:
func: The teardown websocket function itself.
name: Optional blueprint key name.
"""
self.teardown_websocket_funcs[None].append(func)
return func
@setupmethod
def before_app_websocket(self, func: T_before_websocket) -> 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 :meth:`~quart.Quart.before_websocket`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_websocket
def before():
...
"""
self.record_once(lambda state: state.app.before_websocket(func)) # type: ignore
return func
@setupmethod
def before_app_serving(self, func: T_before_serving) -> 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 :meth:`~quart.Quart.before_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_serving
def before():
...
"""
self.record_once(lambda state: state.app.before_serving(func)) # type: ignore
return func
@setupmethod
def after_app_websocket(self, func: T_after_websocket) -> 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 :meth:`~quart.Quart.after_websocket`. It applies to all requests to the
ppe this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_websocket
def after():
...
"""
self.record_once(lambda state: state.app.after_websocket(func)) # type: ignore
return func
@setupmethod
def after_app_serving(self, func: T_after_serving) -> 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 :meth:`~quart.Quart.after_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_serving
def after():
...
"""
self.record_once(lambda state: state.app.after_serving(func)) # type: ignore[attr-defined]
return func
@setupmethod
def while_app_serving(self, func: T_while_serving) -> 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 :meth:`~quart.Quart.while_serving`. An example usage,
.. code-block:: python
@blueprint.while_serving
async def func():
... # Startup
yield
... # Shutdown
"""
self.record_once(lambda state: state.app.while_serving(func)) # type: ignore[attr-defined]
return func
@setupmethod
def teardown_app_websocket(self, func: T_teardown) -> 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 :meth:`~quart.Quart.teardown_websocket`. It applies
to all requests to the app this blueprint is registered on. An
example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.teardown_app_websocket
def teardown():
...
"""
self.record_once(lambda state: state.app.teardown_websocket(func)) # type: ignore
return func
def _merge_blueprint_funcs(self, app: App, name: str) -> None:
super()._merge_blueprint_funcs(app, name)
def extend(bp_dict: dict, parent_dict: dict) -> None:
for key, values in bp_dict.items():
key = name if key is None else f"{name}.{key}"
parent_dict[key].extend(values)
for key, value in self.error_handler_spec.items():
key = name if key is None else f"{name}.{key}"
value = defaultdict(
dict,
{
code: {exc_class: func for exc_class, func in code_values.items()}
for code, code_values in value.items()
},
)
app.error_handler_spec[key] = value
extend(self.before_websocket_funcs, app.before_websocket_funcs) # type: ignore
extend(self.after_websocket_funcs, app.after_websocket_funcs) # type: ignore
| (self, func: ~T_teardown) -> ~T_teardown |
29,263 | quart.blueprints | teardown_websocket | Add a teardown websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.teardown_websocket
async def func():
...
Arguments:
func: The teardown websocket function itself.
name: Optional blueprint key name.
| from __future__ import annotations
import os
import typing as t
from collections import defaultdict
from datetime import timedelta
from aiofiles import open as async_open
from aiofiles.base import AiofilesContextManager
from aiofiles.threadpool.binary import AsyncBufferedReader
from flask.sansio.app import App
from flask.sansio.blueprints import ( # noqa
Blueprint as SansioBlueprint,
BlueprintSetupState as BlueprintSetupState,
)
from flask.sansio.scaffold import setupmethod
from .cli import AppGroup
from .globals import current_app
from .helpers import send_from_directory
from .typing import (
AfterServingCallable,
AfterWebsocketCallable,
AppOrBlueprintKey,
BeforeServingCallable,
BeforeWebsocketCallable,
FilePath,
TeardownCallable,
WebsocketCallable,
WhileServingCallable,
)
if t.TYPE_CHECKING:
from .wrappers import Response
T_after_serving = t.TypeVar("T_after_serving", bound=AfterServingCallable)
T_after_websocket = t.TypeVar("T_after_websocket", bound=AfterWebsocketCallable)
T_before_serving = t.TypeVar("T_before_serving", bound=BeforeServingCallable)
T_before_websocket = t.TypeVar("T_before_websocket", bound=BeforeWebsocketCallable)
T_teardown = t.TypeVar("T_teardown", bound=TeardownCallable)
T_websocket = t.TypeVar("T_websocket", bound=WebsocketCallable)
T_while_serving = t.TypeVar("T_while_serving", bound=WhileServingCallable)
class Blueprint(SansioBlueprint):
"""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.
"""
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
super().__init__(*args, **kwargs)
self.cli = AppGroup()
self.cli.name = self.name
self.after_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[AfterWebsocketCallable]] = (
defaultdict(list)
)
self.before_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[BeforeWebsocketCallable]] = (
defaultdict(list)
)
self.teardown_websocket_funcs: dict[AppOrBlueprintKey, list[TeardownCallable]] = (
defaultdict(list)
)
def get_send_file_max_age(self, filename: str | None) -> int | None:
"""Used by :func:`send_file` to determine the ``max_age`` cache
value for a given file path if it wasn't passed.
By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
the configuration of :data:`~flask.current_app`. This defaults
to ``None``, which tells the browser to use conditional requests
instead of a timed cache, which is usually preferable.
Note this is a duplicate of the same method in the Quart
class.
"""
value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]
if value is None:
return None
if isinstance(value, timedelta):
return int(value.total_seconds())
return value
return None
async def send_static_file(self, filename: str) -> Response:
if not self.has_static_folder:
raise RuntimeError("No static folder for this object")
return await send_from_directory(self.static_folder, filename)
async def open_resource(
self,
path: FilePath,
mode: str = "rb",
) -> AiofilesContextManager[None, None, AsyncBufferedReader]:
"""Open a file for reading.
Use as
.. code-block:: python
async with await app.open_resource(path) as file_:
await file_.read()
"""
if mode not in {"r", "rb", "rt"}:
raise ValueError("Files can only be opened for reading")
return async_open(os.path.join(self.root_path, path), mode) # type: ignore
def websocket(
self,
rule: str,
**options: t.Any,
) -> t.Callable[[T_websocket], T_websocket]:
"""Add a websocket to the application.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.websocket('/')
async def websocket_route():
...
Arguments:
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``,
.. code-block:: python
@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).
"""
def decorator(func: T_websocket) -> T_websocket:
endpoint = options.pop("endpoint", None)
self.add_websocket(
rule,
endpoint,
func,
**options,
)
return func
return decorator
def add_websocket(
self,
rule: str,
endpoint: str | None = None,
view_func: WebsocketCallable | None = None,
**options: t.Any,
) -> None:
"""Add a websocket url rule to the application.
This is designed to be used on the application directly. An
example usage,
.. code-block:: python
def websocket_route():
...
app.add_websocket('/', websocket_route)
Arguments:
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``,
.. code-block:: python
@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).
"""
return self.add_url_rule(
rule,
endpoint,
view_func,
methods={"GET"},
websocket=True,
**options,
)
@setupmethod
def before_websocket(
self,
func: T_before_websocket,
) -> T_before_websocket:
"""Add a before websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.before_websocket
async def func():
...
Arguments:
func: The before websocket function itself.
"""
self.before_websocket_funcs[None].append(func)
return func
@setupmethod
def after_websocket(
self,
func: T_after_websocket,
) -> T_after_websocket:
"""Add an after websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.after_websocket
async def func(response):
return response
Arguments:
func: The after websocket function itself.
"""
self.after_websocket_funcs[None].append(func)
return func
@setupmethod
def teardown_websocket(
self,
func: T_teardown,
) -> T_teardown:
"""Add a teardown websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.teardown_websocket
async def func():
...
Arguments:
func: The teardown websocket function itself.
name: Optional blueprint key name.
"""
self.teardown_websocket_funcs[None].append(func)
return func
@setupmethod
def before_app_websocket(self, func: T_before_websocket) -> 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 :meth:`~quart.Quart.before_websocket`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_websocket
def before():
...
"""
self.record_once(lambda state: state.app.before_websocket(func)) # type: ignore
return func
@setupmethod
def before_app_serving(self, func: T_before_serving) -> 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 :meth:`~quart.Quart.before_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_serving
def before():
...
"""
self.record_once(lambda state: state.app.before_serving(func)) # type: ignore
return func
@setupmethod
def after_app_websocket(self, func: T_after_websocket) -> 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 :meth:`~quart.Quart.after_websocket`. It applies to all requests to the
ppe this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_websocket
def after():
...
"""
self.record_once(lambda state: state.app.after_websocket(func)) # type: ignore
return func
@setupmethod
def after_app_serving(self, func: T_after_serving) -> 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 :meth:`~quart.Quart.after_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_serving
def after():
...
"""
self.record_once(lambda state: state.app.after_serving(func)) # type: ignore[attr-defined]
return func
@setupmethod
def while_app_serving(self, func: T_while_serving) -> 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 :meth:`~quart.Quart.while_serving`. An example usage,
.. code-block:: python
@blueprint.while_serving
async def func():
... # Startup
yield
... # Shutdown
"""
self.record_once(lambda state: state.app.while_serving(func)) # type: ignore[attr-defined]
return func
@setupmethod
def teardown_app_websocket(self, func: T_teardown) -> 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 :meth:`~quart.Quart.teardown_websocket`. It applies
to all requests to the app this blueprint is registered on. An
example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.teardown_app_websocket
def teardown():
...
"""
self.record_once(lambda state: state.app.teardown_websocket(func)) # type: ignore
return func
def _merge_blueprint_funcs(self, app: App, name: str) -> None:
super()._merge_blueprint_funcs(app, name)
def extend(bp_dict: dict, parent_dict: dict) -> None:
for key, values in bp_dict.items():
key = name if key is None else f"{name}.{key}"
parent_dict[key].extend(values)
for key, value in self.error_handler_spec.items():
key = name if key is None else f"{name}.{key}"
value = defaultdict(
dict,
{
code: {exc_class: func for exc_class, func in code_values.items()}
for code, code_values in value.items()
},
)
app.error_handler_spec[key] = value
extend(self.before_websocket_funcs, app.before_websocket_funcs) # type: ignore
extend(self.after_websocket_funcs, app.after_websocket_funcs) # type: ignore
| (self, func: ~T_teardown) -> ~T_teardown |
29,266 | quart.blueprints | websocket | Add a websocket to the application.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.websocket('/')
async def websocket_route():
...
Arguments:
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``,
.. code-block:: python
@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).
| def websocket(
self,
rule: str,
**options: t.Any,
) -> t.Callable[[T_websocket], T_websocket]:
"""Add a websocket to the application.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.websocket('/')
async def websocket_route():
...
Arguments:
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``,
.. code-block:: python
@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).
"""
def decorator(func: T_websocket) -> T_websocket:
endpoint = options.pop("endpoint", None)
self.add_websocket(
rule,
endpoint,
func,
**options,
)
return func
return decorator
| (self, rule: str, **options: Any) -> Callable[[~T_websocket], ~T_websocket] |
29,267 | quart.blueprints | while_app_serving | Add a while serving function to the App.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.while_serving`. An example usage,
.. code-block:: python
@blueprint.while_serving
async def func():
... # Startup
yield
... # Shutdown
| from __future__ import annotations
import os
import typing as t
from collections import defaultdict
from datetime import timedelta
from aiofiles import open as async_open
from aiofiles.base import AiofilesContextManager
from aiofiles.threadpool.binary import AsyncBufferedReader
from flask.sansio.app import App
from flask.sansio.blueprints import ( # noqa
Blueprint as SansioBlueprint,
BlueprintSetupState as BlueprintSetupState,
)
from flask.sansio.scaffold import setupmethod
from .cli import AppGroup
from .globals import current_app
from .helpers import send_from_directory
from .typing import (
AfterServingCallable,
AfterWebsocketCallable,
AppOrBlueprintKey,
BeforeServingCallable,
BeforeWebsocketCallable,
FilePath,
TeardownCallable,
WebsocketCallable,
WhileServingCallable,
)
if t.TYPE_CHECKING:
from .wrappers import Response
T_after_serving = t.TypeVar("T_after_serving", bound=AfterServingCallable)
T_after_websocket = t.TypeVar("T_after_websocket", bound=AfterWebsocketCallable)
T_before_serving = t.TypeVar("T_before_serving", bound=BeforeServingCallable)
T_before_websocket = t.TypeVar("T_before_websocket", bound=BeforeWebsocketCallable)
T_teardown = t.TypeVar("T_teardown", bound=TeardownCallable)
T_websocket = t.TypeVar("T_websocket", bound=WebsocketCallable)
T_while_serving = t.TypeVar("T_while_serving", bound=WhileServingCallable)
class Blueprint(SansioBlueprint):
"""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.
"""
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
super().__init__(*args, **kwargs)
self.cli = AppGroup()
self.cli.name = self.name
self.after_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[AfterWebsocketCallable]] = (
defaultdict(list)
)
self.before_websocket_funcs: t.Dict[AppOrBlueprintKey, t.List[BeforeWebsocketCallable]] = (
defaultdict(list)
)
self.teardown_websocket_funcs: dict[AppOrBlueprintKey, list[TeardownCallable]] = (
defaultdict(list)
)
def get_send_file_max_age(self, filename: str | None) -> int | None:
"""Used by :func:`send_file` to determine the ``max_age`` cache
value for a given file path if it wasn't passed.
By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
the configuration of :data:`~flask.current_app`. This defaults
to ``None``, which tells the browser to use conditional requests
instead of a timed cache, which is usually preferable.
Note this is a duplicate of the same method in the Quart
class.
"""
value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]
if value is None:
return None
if isinstance(value, timedelta):
return int(value.total_seconds())
return value
return None
async def send_static_file(self, filename: str) -> Response:
if not self.has_static_folder:
raise RuntimeError("No static folder for this object")
return await send_from_directory(self.static_folder, filename)
async def open_resource(
self,
path: FilePath,
mode: str = "rb",
) -> AiofilesContextManager[None, None, AsyncBufferedReader]:
"""Open a file for reading.
Use as
.. code-block:: python
async with await app.open_resource(path) as file_:
await file_.read()
"""
if mode not in {"r", "rb", "rt"}:
raise ValueError("Files can only be opened for reading")
return async_open(os.path.join(self.root_path, path), mode) # type: ignore
def websocket(
self,
rule: str,
**options: t.Any,
) -> t.Callable[[T_websocket], T_websocket]:
"""Add a websocket to the application.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.websocket('/')
async def websocket_route():
...
Arguments:
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``,
.. code-block:: python
@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).
"""
def decorator(func: T_websocket) -> T_websocket:
endpoint = options.pop("endpoint", None)
self.add_websocket(
rule,
endpoint,
func,
**options,
)
return func
return decorator
def add_websocket(
self,
rule: str,
endpoint: str | None = None,
view_func: WebsocketCallable | None = None,
**options: t.Any,
) -> None:
"""Add a websocket url rule to the application.
This is designed to be used on the application directly. An
example usage,
.. code-block:: python
def websocket_route():
...
app.add_websocket('/', websocket_route)
Arguments:
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``,
.. code-block:: python
@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).
"""
return self.add_url_rule(
rule,
endpoint,
view_func,
methods={"GET"},
websocket=True,
**options,
)
@setupmethod
def before_websocket(
self,
func: T_before_websocket,
) -> T_before_websocket:
"""Add a before websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.before_websocket
async def func():
...
Arguments:
func: The before websocket function itself.
"""
self.before_websocket_funcs[None].append(func)
return func
@setupmethod
def after_websocket(
self,
func: T_after_websocket,
) -> T_after_websocket:
"""Add an after websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.after_websocket
async def func(response):
return response
Arguments:
func: The after websocket function itself.
"""
self.after_websocket_funcs[None].append(func)
return func
@setupmethod
def teardown_websocket(
self,
func: T_teardown,
) -> T_teardown:
"""Add a teardown websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.teardown_websocket
async def func():
...
Arguments:
func: The teardown websocket function itself.
name: Optional blueprint key name.
"""
self.teardown_websocket_funcs[None].append(func)
return func
@setupmethod
def before_app_websocket(self, func: T_before_websocket) -> 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 :meth:`~quart.Quart.before_websocket`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_websocket
def before():
...
"""
self.record_once(lambda state: state.app.before_websocket(func)) # type: ignore
return func
@setupmethod
def before_app_serving(self, func: T_before_serving) -> 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 :meth:`~quart.Quart.before_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_serving
def before():
...
"""
self.record_once(lambda state: state.app.before_serving(func)) # type: ignore
return func
@setupmethod
def after_app_websocket(self, func: T_after_websocket) -> 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 :meth:`~quart.Quart.after_websocket`. It applies to all requests to the
ppe this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_websocket
def after():
...
"""
self.record_once(lambda state: state.app.after_websocket(func)) # type: ignore
return func
@setupmethod
def after_app_serving(self, func: T_after_serving) -> 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 :meth:`~quart.Quart.after_serving`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_serving
def after():
...
"""
self.record_once(lambda state: state.app.after_serving(func)) # type: ignore[attr-defined]
return func
@setupmethod
def while_app_serving(self, func: T_while_serving) -> 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 :meth:`~quart.Quart.while_serving`. An example usage,
.. code-block:: python
@blueprint.while_serving
async def func():
... # Startup
yield
... # Shutdown
"""
self.record_once(lambda state: state.app.while_serving(func)) # type: ignore[attr-defined]
return func
@setupmethod
def teardown_app_websocket(self, func: T_teardown) -> 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 :meth:`~quart.Quart.teardown_websocket`. It applies
to all requests to the app this blueprint is registered on. An
example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.teardown_app_websocket
def teardown():
...
"""
self.record_once(lambda state: state.app.teardown_websocket(func)) # type: ignore
return func
def _merge_blueprint_funcs(self, app: App, name: str) -> None:
super()._merge_blueprint_funcs(app, name)
def extend(bp_dict: dict, parent_dict: dict) -> None:
for key, values in bp_dict.items():
key = name if key is None else f"{name}.{key}"
parent_dict[key].extend(values)
for key, value in self.error_handler_spec.items():
key = name if key is None else f"{name}.{key}"
value = defaultdict(
dict,
{
code: {exc_class: func for exc_class, func in code_values.items()}
for code, code_values in value.items()
},
)
app.error_handler_spec[key] = value
extend(self.before_websocket_funcs, app.before_websocket_funcs) # type: ignore
extend(self.after_websocket_funcs, app.after_websocket_funcs) # type: ignore
| (self, func: ~T_while_serving) -> ~T_while_serving |
29,268 | quart.config | Config | null | class Config(FlaskConfig):
def from_prefixed_env(
self, prefix: str = "QUART", *, loads: Callable[[str], Any] = json.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 :func:`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.
Arguments:
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 :func:`json.loads`.
"""
return super().from_prefixed_env(prefix, loads=loads)
| (root_path: 'str | os.PathLike[str]', defaults: 'dict[str, t.Any] | None' = None) -> 'None' |
29,269 | flask.config | __init__ | null | def __init__(
self,
root_path: str | os.PathLike[str],
defaults: dict[str, t.Any] | None = None,
) -> None:
super().__init__(defaults or {})
self.root_path = root_path
| (self, root_path: str | os.PathLike[str], defaults: Optional[dict[str, Any]] = None) -> NoneType |
29,270 | flask.config | __repr__ | null | def __repr__(self) -> str:
return f"<{type(self).__name__} {dict.__repr__(self)}>"
| (self) -> str |
29,271 | flask.config | from_envvar | Loads a configuration from an environment variable pointing to
a configuration file. This is basically just a shortcut with nicer
error messages for this line of code::
app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
:param variable_name: name of the environment variable
:param silent: set to ``True`` if you want silent failure for missing
files.
:return: ``True`` if the file was loaded successfully.
| def from_envvar(self, variable_name: str, silent: bool = False) -> bool:
"""Loads a configuration from an environment variable pointing to
a configuration file. This is basically just a shortcut with nicer
error messages for this line of code::
app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
:param variable_name: name of the environment variable
:param silent: set to ``True`` if you want silent failure for missing
files.
:return: ``True`` if the file was loaded successfully.
"""
rv = os.environ.get(variable_name)
if not rv:
if silent:
return False
raise RuntimeError(
f"The environment variable {variable_name!r} is not set"
" and as such configuration could not be loaded. Set"
" this variable and make it point to a configuration"
" file"
)
return self.from_pyfile(rv, silent=silent)
| (self, variable_name: str, silent: bool = False) -> bool |
29,272 | flask.config | from_file | Update the values in the config from a file that is loaded
using the ``load`` parameter. The loaded data is passed to the
:meth:`from_mapping` method.
.. code-block:: python
import json
app.config.from_file("config.json", load=json.load)
import tomllib
app.config.from_file("config.toml", load=tomllib.load, text=False)
:param filename: The path to the data file. This can be an
absolute path or relative to the config root path.
:param load: A callable that takes a file handle and returns a
mapping of loaded data from the file.
:type load: ``Callable[[Reader], Mapping]`` where ``Reader``
implements a ``read`` method.
:param silent: Ignore the file if it doesn't exist.
:param text: Open the file in text or binary mode.
:return: ``True`` if the file was loaded successfully.
.. versionchanged:: 2.3
The ``text`` parameter was added.
.. versionadded:: 2.0
| def from_file(
self,
filename: str | os.PathLike[str],
load: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]],
silent: bool = False,
text: bool = True,
) -> bool:
"""Update the values in the config from a file that is loaded
using the ``load`` parameter. The loaded data is passed to the
:meth:`from_mapping` method.
.. code-block:: python
import json
app.config.from_file("config.json", load=json.load)
import tomllib
app.config.from_file("config.toml", load=tomllib.load, text=False)
:param filename: The path to the data file. This can be an
absolute path or relative to the config root path.
:param load: A callable that takes a file handle and returns a
mapping of loaded data from the file.
:type load: ``Callable[[Reader], Mapping]`` where ``Reader``
implements a ``read`` method.
:param silent: Ignore the file if it doesn't exist.
:param text: Open the file in text or binary mode.
:return: ``True`` if the file was loaded successfully.
.. versionchanged:: 2.3
The ``text`` parameter was added.
.. versionadded:: 2.0
"""
filename = os.path.join(self.root_path, filename)
try:
with open(filename, "r" if text else "rb") as f:
obj = load(f)
except OSError as e:
if silent and e.errno in (errno.ENOENT, errno.EISDIR):
return False
e.strerror = f"Unable to load configuration file ({e.strerror})"
raise
return self.from_mapping(obj)
| (self, filename: str | os.PathLike[str], load: Callable[[IO[Any]], Mapping[str, Any]], silent: bool = False, text: bool = True) -> bool |
29,273 | flask.config | from_mapping | Updates the config like :meth:`update` ignoring items with
non-upper keys.
:return: Always returns ``True``.
.. versionadded:: 0.11
| def from_mapping(
self, mapping: t.Mapping[str, t.Any] | None = None, **kwargs: t.Any
) -> bool:
"""Updates the config like :meth:`update` ignoring items with
non-upper keys.
:return: Always returns ``True``.
.. versionadded:: 0.11
"""
mappings: dict[str, t.Any] = {}
if mapping is not None:
mappings.update(mapping)
mappings.update(kwargs)
for key, value in mappings.items():
if key.isupper():
self[key] = value
return True
| (self, mapping: Optional[Mapping[str, Any]] = None, **kwargs: Any) -> bool |
29,274 | flask.config | from_object | Updates the values from the given object. An object can be of one
of the following two types:
- a string: in this case the object with that name will be imported
- an actual object reference: that object is used directly
Objects are usually either modules or classes. :meth:`from_object`
loads only the uppercase attributes of the module/class. A ``dict``
object will not work with :meth:`from_object` because the keys of a
``dict`` are not attributes of the ``dict`` class.
Example of module-based configuration::
app.config.from_object('yourapplication.default_config')
from yourapplication import default_config
app.config.from_object(default_config)
Nothing is done to the object before loading. If the object is a
class and has ``@property`` attributes, it needs to be
instantiated before being passed to this method.
You should not use this function to load the actual configuration but
rather configuration defaults. The actual config should be loaded
with :meth:`from_pyfile` and ideally from a location not within the
package because the package might be installed system wide.
See :ref:`config-dev-prod` for an example of class-based configuration
using :meth:`from_object`.
:param obj: an import name or object
| def from_object(self, obj: object | str) -> None:
"""Updates the values from the given object. An object can be of one
of the following two types:
- a string: in this case the object with that name will be imported
- an actual object reference: that object is used directly
Objects are usually either modules or classes. :meth:`from_object`
loads only the uppercase attributes of the module/class. A ``dict``
object will not work with :meth:`from_object` because the keys of a
``dict`` are not attributes of the ``dict`` class.
Example of module-based configuration::
app.config.from_object('yourapplication.default_config')
from yourapplication import default_config
app.config.from_object(default_config)
Nothing is done to the object before loading. If the object is a
class and has ``@property`` attributes, it needs to be
instantiated before being passed to this method.
You should not use this function to load the actual configuration but
rather configuration defaults. The actual config should be loaded
with :meth:`from_pyfile` and ideally from a location not within the
package because the package might be installed system wide.
See :ref:`config-dev-prod` for an example of class-based configuration
using :meth:`from_object`.
:param obj: an import name or object
"""
if isinstance(obj, str):
obj = import_string(obj)
for key in dir(obj):
if key.isupper():
self[key] = getattr(obj, key)
| (self, obj: object | str) -> NoneType |
29,275 | quart.config | from_prefixed_env | 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 :func:`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.
Arguments:
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 :func:`json.loads`.
| def from_prefixed_env(
self, prefix: str = "QUART", *, loads: Callable[[str], Any] = json.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 :func:`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.
Arguments:
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 :func:`json.loads`.
"""
return super().from_prefixed_env(prefix, loads=loads)
| (self, prefix: str = 'QUART', *, loads: Callable[[str], Any] = <function loads at 0x7fa595c0d120>) -> bool |
29,276 | flask.config | from_pyfile | Updates the values in the config from a Python file. This function
behaves as if the file was imported as module with the
:meth:`from_object` function.
:param filename: the filename of the config. This can either be an
absolute filename or a filename relative to the
root path.
:param silent: set to ``True`` if you want silent failure for missing
files.
:return: ``True`` if the file was loaded successfully.
.. versionadded:: 0.7
`silent` parameter.
| def from_pyfile(
self, filename: str | os.PathLike[str], silent: bool = False
) -> bool:
"""Updates the values in the config from a Python file. This function
behaves as if the file was imported as module with the
:meth:`from_object` function.
:param filename: the filename of the config. This can either be an
absolute filename or a filename relative to the
root path.
:param silent: set to ``True`` if you want silent failure for missing
files.
:return: ``True`` if the file was loaded successfully.
.. versionadded:: 0.7
`silent` parameter.
"""
filename = os.path.join(self.root_path, filename)
d = types.ModuleType("config")
d.__file__ = filename
try:
with open(filename, mode="rb") as config_file:
exec(compile(config_file.read(), filename, "exec"), d.__dict__)
except OSError as e:
if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):
return False
e.strerror = f"Unable to load configuration file ({e.strerror})"
raise
self.from_object(d)
return True
| (self, filename: str | os.PathLike[str], silent: bool = False) -> bool |
29,277 | flask.config | get_namespace | Returns a dictionary containing a subset of configuration options
that match the specified namespace/prefix. Example usage::
app.config['IMAGE_STORE_TYPE'] = 'fs'
app.config['IMAGE_STORE_PATH'] = '/var/app/images'
app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
image_store_config = app.config.get_namespace('IMAGE_STORE_')
The resulting dictionary `image_store_config` would look like::
{
'type': 'fs',
'path': '/var/app/images',
'base_url': 'http://img.website.com'
}
This is often useful when configuration options map directly to
keyword arguments in functions or class constructors.
:param namespace: a configuration namespace
:param lowercase: a flag indicating if the keys of the resulting
dictionary should be lowercase
:param trim_namespace: a flag indicating if the keys of the resulting
dictionary should not include the namespace
.. versionadded:: 0.11
| def get_namespace(
self, namespace: str, lowercase: bool = True, trim_namespace: bool = True
) -> dict[str, t.Any]:
"""Returns a dictionary containing a subset of configuration options
that match the specified namespace/prefix. Example usage::
app.config['IMAGE_STORE_TYPE'] = 'fs'
app.config['IMAGE_STORE_PATH'] = '/var/app/images'
app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
image_store_config = app.config.get_namespace('IMAGE_STORE_')
The resulting dictionary `image_store_config` would look like::
{
'type': 'fs',
'path': '/var/app/images',
'base_url': 'http://img.website.com'
}
This is often useful when configuration options map directly to
keyword arguments in functions or class constructors.
:param namespace: a configuration namespace
:param lowercase: a flag indicating if the keys of the resulting
dictionary should be lowercase
:param trim_namespace: a flag indicating if the keys of the resulting
dictionary should not include the namespace
.. versionadded:: 0.11
"""
rv = {}
for k, v in self.items():
if not k.startswith(namespace):
continue
if trim_namespace:
key = k[len(namespace) :]
else:
key = k
if lowercase:
key = key.lower()
rv[key] = v
return rv
| (self, namespace: str, lowercase: bool = True, trim_namespace: bool = True) -> dict[str, typing.Any] |
29,278 | markupsafe | Markup | 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
:meth:`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 :class:`str`. It has the same methods, but
escapes their arguments and returns a ``Markup`` instance.
>>> Markup("<em>%s</em>") % ("foo & bar",)
Markup('<em>foo & bar</em>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup('<em>Hello</em> <foo>')
| class Markup(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
:meth:`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 :class:`str`. It has the same methods, but
escapes their arguments and returns a ``Markup`` instance.
>>> Markup("<em>%s</em>") % ("foo & bar",)
Markup('<em>foo & bar</em>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup('<em>Hello</em> <foo>')
"""
__slots__ = ()
def __new__(
cls, base: t.Any = "", encoding: t.Optional[str] = None, errors: str = "strict"
) -> "te.Self":
if hasattr(base, "__html__"):
base = base.__html__()
if encoding is None:
return super().__new__(cls, base)
return super().__new__(cls, base, encoding, errors)
def __html__(self) -> "te.Self":
return self
def __add__(self, other: t.Union[str, "HasHTML"]) -> "te.Self":
if isinstance(other, str) or hasattr(other, "__html__"):
return self.__class__(super().__add__(self.escape(other)))
return NotImplemented
def __radd__(self, other: t.Union[str, "HasHTML"]) -> "te.Self":
if isinstance(other, str) or hasattr(other, "__html__"):
return self.escape(other).__add__(self)
return NotImplemented
def __mul__(self, num: "te.SupportsIndex") -> "te.Self":
if isinstance(num, int):
return self.__class__(super().__mul__(num))
return NotImplemented
__rmul__ = __mul__
def __mod__(self, arg: t.Any) -> "te.Self":
if isinstance(arg, tuple):
# a tuple of arguments, each wrapped
arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg)
elif hasattr(type(arg), "__getitem__") and not isinstance(arg, str):
# a mapping of arguments, wrapped
arg = _MarkupEscapeHelper(arg, self.escape)
else:
# a single argument, wrapped with the helper and a tuple
arg = (_MarkupEscapeHelper(arg, self.escape),)
return self.__class__(super().__mod__(arg))
def __repr__(self) -> str:
return f"{self.__class__.__name__}({super().__repr__()})"
def join(self, seq: t.Iterable[t.Union[str, "HasHTML"]]) -> "te.Self":
return self.__class__(super().join(map(self.escape, seq)))
join.__doc__ = str.join.__doc__
def split( # type: ignore[override]
self, sep: t.Optional[str] = None, maxsplit: int = -1
) -> t.List["te.Self"]:
return [self.__class__(v) for v in super().split(sep, maxsplit)]
split.__doc__ = str.split.__doc__
def rsplit( # type: ignore[override]
self, sep: t.Optional[str] = None, maxsplit: int = -1
) -> t.List["te.Self"]:
return [self.__class__(v) for v in super().rsplit(sep, maxsplit)]
rsplit.__doc__ = str.rsplit.__doc__
def splitlines( # type: ignore[override]
self, keepends: bool = False
) -> t.List["te.Self"]:
return [self.__class__(v) for v in super().splitlines(keepends)]
splitlines.__doc__ = str.splitlines.__doc__
def unescape(self) -> 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>'
"""
from html import unescape
return unescape(str(self))
def striptags(self) -> str:
""":meth:`unescape` the markup, remove tags, and normalize
whitespace to single spaces.
>>> Markup("Main »\t<em>About</em>").striptags()
'Main » About'
"""
value = str(self)
# Look for comments then tags separately. Otherwise, a comment that
# contains a tag would end early, leaving some of the comment behind.
while True:
# keep finding comment start marks
start = value.find("<!--")
if start == -1:
break
# find a comment end mark beyond the start, otherwise stop
end = value.find("-->", start)
if end == -1:
break
value = f"{value[:start]}{value[end + 3:]}"
# remove tags using the same method
while True:
start = value.find("<")
if start == -1:
break
end = value.find(">", start)
if end == -1:
break
value = f"{value[:start]}{value[end + 1:]}"
# collapse spaces
value = " ".join(value.split())
return self.__class__(value).unescape()
@classmethod
def escape(cls, s: t.Any) -> "te.Self":
"""Escape a string. Calls :func:`escape` and ensures that for
subclasses the correct type is returned.
"""
rv = escape(s)
if rv.__class__ is not cls:
return cls(rv)
return rv # type: ignore[return-value]
__getitem__ = _simple_escaping_wrapper(str.__getitem__)
capitalize = _simple_escaping_wrapper(str.capitalize)
title = _simple_escaping_wrapper(str.title)
lower = _simple_escaping_wrapper(str.lower)
upper = _simple_escaping_wrapper(str.upper)
replace = _simple_escaping_wrapper(str.replace)
ljust = _simple_escaping_wrapper(str.ljust)
rjust = _simple_escaping_wrapper(str.rjust)
lstrip = _simple_escaping_wrapper(str.lstrip)
rstrip = _simple_escaping_wrapper(str.rstrip)
center = _simple_escaping_wrapper(str.center)
strip = _simple_escaping_wrapper(str.strip)
translate = _simple_escaping_wrapper(str.translate)
expandtabs = _simple_escaping_wrapper(str.expandtabs)
swapcase = _simple_escaping_wrapper(str.swapcase)
zfill = _simple_escaping_wrapper(str.zfill)
casefold = _simple_escaping_wrapper(str.casefold)
if sys.version_info >= (3, 9):
removeprefix = _simple_escaping_wrapper(str.removeprefix)
removesuffix = _simple_escaping_wrapper(str.removesuffix)
def partition(self, sep: str) -> t.Tuple["te.Self", "te.Self", "te.Self"]:
l, s, r = super().partition(self.escape(sep))
cls = self.__class__
return cls(l), cls(s), cls(r)
def rpartition(self, sep: str) -> t.Tuple["te.Self", "te.Self", "te.Self"]:
l, s, r = super().rpartition(self.escape(sep))
cls = self.__class__
return cls(l), cls(s), cls(r)
def format(self, *args: t.Any, **kwargs: t.Any) -> "te.Self":
formatter = EscapeFormatter(self.escape)
return self.__class__(formatter.vformat(self, args, kwargs))
def format_map( # type: ignore[override]
self, map: t.Mapping[str, t.Any]
) -> "te.Self":
formatter = EscapeFormatter(self.escape)
return self.__class__(formatter.vformat(self, (), map))
def __html_format__(self, format_spec: str) -> "te.Self":
if format_spec:
raise ValueError("Unsupported format specification for Markup.")
return self
| (base: Any = '', encoding: Optional[str] = None, errors: str = 'strict') -> 'te.Self' |
29,279 | markupsafe | __add__ | null | def __add__(self, other: t.Union[str, "HasHTML"]) -> "te.Self":
if isinstance(other, str) or hasattr(other, "__html__"):
return self.__class__(super().__add__(self.escape(other)))
return NotImplemented
| (self, other: Union[str, ForwardRef('HasHTML')]) -> 'te.Self' |
29,280 | markupsafe | __getitem__ | Return self[key]. | def _simple_escaping_wrapper(func: "t.Callable[_P, str]") -> "t.Callable[_P, Markup]":
@functools.wraps(func)
def wrapped(self: "Markup", *args: "_P.args", **kwargs: "_P.kwargs") -> "Markup":
arg_list = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, kwargs.items(), self.escape)
return self.__class__(func(self, *arg_list, **kwargs)) # type: ignore[arg-type]
return wrapped # type: ignore[return-value]
| (self, key, /) |
29,281 | markupsafe | __html__ | null | def __html__(self) -> "te.Self":
return self
| (self) -> 'te.Self' |
29,282 | markupsafe | __html_format__ | null | def __html_format__(self, format_spec: str) -> "te.Self":
if format_spec:
raise ValueError("Unsupported format specification for Markup.")
return self
| (self, format_spec: str) -> 'te.Self' |
29,283 | markupsafe | __mod__ | null | def __mod__(self, arg: t.Any) -> "te.Self":
if isinstance(arg, tuple):
# a tuple of arguments, each wrapped
arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg)
elif hasattr(type(arg), "__getitem__") and not isinstance(arg, str):
# a mapping of arguments, wrapped
arg = _MarkupEscapeHelper(arg, self.escape)
else:
# a single argument, wrapped with the helper and a tuple
arg = (_MarkupEscapeHelper(arg, self.escape),)
return self.__class__(super().__mod__(arg))
| (self, arg: Any) -> 'te.Self' |
29,284 | markupsafe | __mul__ | null | def __mul__(self, num: "te.SupportsIndex") -> "te.Self":
if isinstance(num, int):
return self.__class__(super().__mul__(num))
return NotImplemented
| (self, num: 'te.SupportsIndex') -> 'te.Self' |
29,285 | markupsafe | __new__ | null | def __new__(
cls, base: t.Any = "", encoding: t.Optional[str] = None, errors: str = "strict"
) -> "te.Self":
if hasattr(base, "__html__"):
base = base.__html__()
if encoding is None:
return super().__new__(cls, base)
return super().__new__(cls, base, encoding, errors)
| (cls, base: Any = '', encoding: Optional[str] = None, errors: str = 'strict') -> 'te.Self' |
29,286 | markupsafe | __radd__ | null | def __radd__(self, other: t.Union[str, "HasHTML"]) -> "te.Self":
if isinstance(other, str) or hasattr(other, "__html__"):
return self.escape(other).__add__(self)
return NotImplemented
| (self, other: Union[str, ForwardRef('HasHTML')]) -> 'te.Self' |
29,287 | markupsafe | __repr__ | null | def __repr__(self) -> str:
return f"{self.__class__.__name__}({super().__repr__()})"
| (self) -> str |
29,289 | markupsafe | capitalize | Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower
case. | def _simple_escaping_wrapper(func: "t.Callable[_P, str]") -> "t.Callable[_P, Markup]":
@functools.wraps(func)
def wrapped(self: "Markup", *args: "_P.args", **kwargs: "_P.kwargs") -> "Markup":
arg_list = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, kwargs.items(), self.escape)
return self.__class__(func(self, *arg_list, **kwargs)) # type: ignore[arg-type]
return wrapped # type: ignore[return-value]
| (self, /) |
29,290 | markupsafe | casefold | Return a version of the string suitable for caseless comparisons. | def _simple_escaping_wrapper(func: "t.Callable[_P, str]") -> "t.Callable[_P, Markup]":
@functools.wraps(func)
def wrapped(self: "Markup", *args: "_P.args", **kwargs: "_P.kwargs") -> "Markup":
arg_list = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, kwargs.items(), self.escape)
return self.__class__(func(self, *arg_list, **kwargs)) # type: ignore[arg-type]
return wrapped # type: ignore[return-value]
| (self, /) |
29,291 | markupsafe | center | Return a centered string of length width.
Padding is done using the specified fill character (default is a space). | def _simple_escaping_wrapper(func: "t.Callable[_P, str]") -> "t.Callable[_P, Markup]":
@functools.wraps(func)
def wrapped(self: "Markup", *args: "_P.args", **kwargs: "_P.kwargs") -> "Markup":
arg_list = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, kwargs.items(), self.escape)
return self.__class__(func(self, *arg_list, **kwargs)) # type: ignore[arg-type]
return wrapped # type: ignore[return-value]
| (self, width, fillchar=' ', /) |
29,292 | markupsafe | expandtabs | Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed. | def _simple_escaping_wrapper(func: "t.Callable[_P, str]") -> "t.Callable[_P, Markup]":
@functools.wraps(func)
def wrapped(self: "Markup", *args: "_P.args", **kwargs: "_P.kwargs") -> "Markup":
arg_list = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, kwargs.items(), self.escape)
return self.__class__(func(self, *arg_list, **kwargs)) # type: ignore[arg-type]
return wrapped # type: ignore[return-value]
| (self, /, tabsize=8) |
29,293 | markupsafe | format | null | def format(self, *args: t.Any, **kwargs: t.Any) -> "te.Self":
formatter = EscapeFormatter(self.escape)
return self.__class__(formatter.vformat(self, args, kwargs))
| (self, *args: Any, **kwargs: Any) -> 'te.Self' |
29,294 | markupsafe | format_map | null | def format_map( # type: ignore[override]
self, map: t.Mapping[str, t.Any]
) -> "te.Self":
formatter = EscapeFormatter(self.escape)
return self.__class__(formatter.vformat(self, (), map))
| (self, map: Mapping[str, Any]) -> 'te.Self' |
29,295 | markupsafe | join | 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' | def join(self, seq: t.Iterable[t.Union[str, "HasHTML"]]) -> "te.Self":
return self.__class__(super().join(map(self.escape, seq)))
| (self, seq: Iterable[Union[str, ForwardRef('HasHTML')]]) -> 'te.Self' |
29,296 | markupsafe | ljust | Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space). | def _simple_escaping_wrapper(func: "t.Callable[_P, str]") -> "t.Callable[_P, Markup]":
@functools.wraps(func)
def wrapped(self: "Markup", *args: "_P.args", **kwargs: "_P.kwargs") -> "Markup":
arg_list = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, kwargs.items(), self.escape)
return self.__class__(func(self, *arg_list, **kwargs)) # type: ignore[arg-type]
return wrapped # type: ignore[return-value]
| (self, width, fillchar=' ', /) |
29,297 | markupsafe | lower | Return a copy of the string converted to lowercase. | def _simple_escaping_wrapper(func: "t.Callable[_P, str]") -> "t.Callable[_P, Markup]":
@functools.wraps(func)
def wrapped(self: "Markup", *args: "_P.args", **kwargs: "_P.kwargs") -> "Markup":
arg_list = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, kwargs.items(), self.escape)
return self.__class__(func(self, *arg_list, **kwargs)) # type: ignore[arg-type]
return wrapped # type: ignore[return-value]
| (self, /) |
29,298 | markupsafe | lstrip | Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead. | def _simple_escaping_wrapper(func: "t.Callable[_P, str]") -> "t.Callable[_P, Markup]":
@functools.wraps(func)
def wrapped(self: "Markup", *args: "_P.args", **kwargs: "_P.kwargs") -> "Markup":
arg_list = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, kwargs.items(), self.escape)
return self.__class__(func(self, *arg_list, **kwargs)) # type: ignore[arg-type]
return wrapped # type: ignore[return-value]
| (self, chars=None, /) |
29,299 | markupsafe | partition | null | def partition(self, sep: str) -> t.Tuple["te.Self", "te.Self", "te.Self"]:
l, s, r = super().partition(self.escape(sep))
cls = self.__class__
return cls(l), cls(s), cls(r)
| (self, sep: str) -> Tuple[ForwardRef('te.Self'), ForwardRef('te.Self'), ForwardRef('te.Self')] |
29,300 | markupsafe | removeprefix | Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):].
Otherwise, return a copy of the original string. | def _simple_escaping_wrapper(func: "t.Callable[_P, str]") -> "t.Callable[_P, Markup]":
@functools.wraps(func)
def wrapped(self: "Markup", *args: "_P.args", **kwargs: "_P.kwargs") -> "Markup":
arg_list = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, kwargs.items(), self.escape)
return self.__class__(func(self, *arg_list, **kwargs)) # type: ignore[arg-type]
return wrapped # type: ignore[return-value]
| (self, prefix, /) |
29,301 | markupsafe | removesuffix | Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty,
return string[:-len(suffix)]. Otherwise, return a copy of the original
string. | def _simple_escaping_wrapper(func: "t.Callable[_P, str]") -> "t.Callable[_P, Markup]":
@functools.wraps(func)
def wrapped(self: "Markup", *args: "_P.args", **kwargs: "_P.kwargs") -> "Markup":
arg_list = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, kwargs.items(), self.escape)
return self.__class__(func(self, *arg_list, **kwargs)) # type: ignore[arg-type]
return wrapped # type: ignore[return-value]
| (self, suffix, /) |
29,302 | markupsafe | replace | 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. | def _simple_escaping_wrapper(func: "t.Callable[_P, str]") -> "t.Callable[_P, Markup]":
@functools.wraps(func)
def wrapped(self: "Markup", *args: "_P.args", **kwargs: "_P.kwargs") -> "Markup":
arg_list = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, kwargs.items(), self.escape)
return self.__class__(func(self, *arg_list, **kwargs)) # type: ignore[arg-type]
return wrapped # type: ignore[return-value]
| (self, old, new, count=-1, /) |
29,303 | markupsafe | rjust | Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space). | def _simple_escaping_wrapper(func: "t.Callable[_P, str]") -> "t.Callable[_P, Markup]":
@functools.wraps(func)
def wrapped(self: "Markup", *args: "_P.args", **kwargs: "_P.kwargs") -> "Markup":
arg_list = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, kwargs.items(), self.escape)
return self.__class__(func(self, *arg_list, **kwargs)) # type: ignore[arg-type]
return wrapped # type: ignore[return-value]
| (self, width, fillchar=' ', /) |
29,304 | markupsafe | rpartition | null | def rpartition(self, sep: str) -> t.Tuple["te.Self", "te.Self", "te.Self"]:
l, s, r = super().rpartition(self.escape(sep))
cls = self.__class__
return cls(l), cls(s), cls(r)
| (self, sep: str) -> Tuple[ForwardRef('te.Self'), ForwardRef('te.Self'), ForwardRef('te.Self')] |
29,305 | markupsafe | rsplit | 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. | def rsplit( # type: ignore[override]
self, sep: t.Optional[str] = None, maxsplit: int = -1
) -> t.List["te.Self"]:
return [self.__class__(v) for v in super().rsplit(sep, maxsplit)]
| (self, sep: Optional[str] = None, maxsplit: int = -1) -> List[ForwardRef('te.Self')] |
29,306 | markupsafe | rstrip | Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead. | def _simple_escaping_wrapper(func: "t.Callable[_P, str]") -> "t.Callable[_P, Markup]":
@functools.wraps(func)
def wrapped(self: "Markup", *args: "_P.args", **kwargs: "_P.kwargs") -> "Markup":
arg_list = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, kwargs.items(), self.escape)
return self.__class__(func(self, *arg_list, **kwargs)) # type: ignore[arg-type]
return wrapped # type: ignore[return-value]
| (self, chars=None, /) |
29,307 | markupsafe | split | 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. | def split( # type: ignore[override]
self, sep: t.Optional[str] = None, maxsplit: int = -1
) -> t.List["te.Self"]:
return [self.__class__(v) for v in super().split(sep, maxsplit)]
| (self, sep: Optional[str] = None, maxsplit: int = -1) -> List[ForwardRef('te.Self')] |
29,308 | markupsafe | splitlines | 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. | def splitlines( # type: ignore[override]
self, keepends: bool = False
) -> t.List["te.Self"]:
return [self.__class__(v) for v in super().splitlines(keepends)]
| (self, keepends: bool = False) -> List[ForwardRef('te.Self')] |
29,309 | markupsafe | strip | Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead. | def _simple_escaping_wrapper(func: "t.Callable[_P, str]") -> "t.Callable[_P, Markup]":
@functools.wraps(func)
def wrapped(self: "Markup", *args: "_P.args", **kwargs: "_P.kwargs") -> "Markup":
arg_list = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, kwargs.items(), self.escape)
return self.__class__(func(self, *arg_list, **kwargs)) # type: ignore[arg-type]
return wrapped # type: ignore[return-value]
| (self, chars=None, /) |
29,310 | markupsafe | striptags | :meth:`unescape` the markup, remove tags, and normalize
whitespace to single spaces.
>>> Markup("Main » <em>About</em>").striptags()
'Main » About'
| def striptags(self) -> str:
""":meth:`unescape` the markup, remove tags, and normalize
whitespace to single spaces.
>>> Markup("Main »\t<em>About</em>").striptags()
'Main » About'
"""
value = str(self)
# Look for comments then tags separately. Otherwise, a comment that
# contains a tag would end early, leaving some of the comment behind.
while True:
# keep finding comment start marks
start = value.find("<!--")
if start == -1:
break
# find a comment end mark beyond the start, otherwise stop
end = value.find("-->", start)
if end == -1:
break
value = f"{value[:start]}{value[end + 3:]}"
# remove tags using the same method
while True:
start = value.find("<")
if start == -1:
break
end = value.find(">", start)
if end == -1:
break
value = f"{value[:start]}{value[end + 1:]}"
# collapse spaces
value = " ".join(value.split())
return self.__class__(value).unescape()
| (self) -> str |
29,311 | markupsafe | swapcase | Convert uppercase characters to lowercase and lowercase characters to uppercase. | def _simple_escaping_wrapper(func: "t.Callable[_P, str]") -> "t.Callable[_P, Markup]":
@functools.wraps(func)
def wrapped(self: "Markup", *args: "_P.args", **kwargs: "_P.kwargs") -> "Markup":
arg_list = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, kwargs.items(), self.escape)
return self.__class__(func(self, *arg_list, **kwargs)) # type: ignore[arg-type]
return wrapped # type: ignore[return-value]
| (self, /) |
29,312 | markupsafe | 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. | def _simple_escaping_wrapper(func: "t.Callable[_P, str]") -> "t.Callable[_P, Markup]":
@functools.wraps(func)
def wrapped(self: "Markup", *args: "_P.args", **kwargs: "_P.kwargs") -> "Markup":
arg_list = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, kwargs.items(), self.escape)
return self.__class__(func(self, *arg_list, **kwargs)) # type: ignore[arg-type]
return wrapped # type: ignore[return-value]
| (self, /) |
29,313 | markupsafe | translate | 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. | def _simple_escaping_wrapper(func: "t.Callable[_P, str]") -> "t.Callable[_P, Markup]":
@functools.wraps(func)
def wrapped(self: "Markup", *args: "_P.args", **kwargs: "_P.kwargs") -> "Markup":
arg_list = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, kwargs.items(), self.escape)
return self.__class__(func(self, *arg_list, **kwargs)) # type: ignore[arg-type]
return wrapped # type: ignore[return-value]
| (self, table, /) |
29,314 | markupsafe | 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>'
| def unescape(self) -> 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>'
"""
from html import unescape
return unescape(str(self))
| (self) -> str |
29,315 | markupsafe | upper | Return a copy of the string converted to uppercase. | def _simple_escaping_wrapper(func: "t.Callable[_P, str]") -> "t.Callable[_P, Markup]":
@functools.wraps(func)
def wrapped(self: "Markup", *args: "_P.args", **kwargs: "_P.kwargs") -> "Markup":
arg_list = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, kwargs.items(), self.escape)
return self.__class__(func(self, *arg_list, **kwargs)) # type: ignore[arg-type]
return wrapped # type: ignore[return-value]
| (self, /) |
29,316 | markupsafe | zfill | Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated. | def _simple_escaping_wrapper(func: "t.Callable[_P, str]") -> "t.Callable[_P, Markup]":
@functools.wraps(func)
def wrapped(self: "Markup", *args: "_P.args", **kwargs: "_P.kwargs") -> "Markup":
arg_list = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, kwargs.items(), self.escape)
return self.__class__(func(self, *arg_list, **kwargs)) # type: ignore[arg-type]
return wrapped # type: ignore[return-value]
| (self, width, /) |
29,317 | quart.app | Quart | The web framework class, handles requests and returns responses.
The primary method from a serving viewpoint is
:meth:`~quart.app.Quart.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.
Attributes:
aborter_class: The class to use to raise HTTP error via the abort
helper function.
app_ctx_globals_class: The class to use for the ``g`` object
asgi_http_class: The class to use to handle the ASGI HTTP
protocol.
asgi_lifespan_class: The class to use to handle the ASGI
lifespan protocol.
asgi_websocket_class: The class to use to handle the ASGI
websocket protocol.
config_class: The class to use for the configuration.
env: The name of the environment the app is running on.
event_class: The class to use to signal an event in an async
manner.
debug: Wrapper around configuration DEBUG value, in many places
this will result in more output if True. If unset, debug
mode will be activated if environ is set to 'development'.
jinja_environment: The class to use for the jinja environment.
jinja_options: The default options to set when creating the jinja
environment.
permanent_session_lifetime: Wrapper around configuration
PERMANENT_SESSION_LIFETIME value. Specifies how long the session
data should survive.
request_class: The class to use for requests.
response_class: The class to user for responses.
secret_key: Warpper around configuration SECRET_KEY value. The app
secret for signing sessions.
session_interface: The class to use as the session interface.
shutdown_event: This event is set when the app starts to
shutdown allowing waiting tasks to know when to stop.
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.
| class Quart(App):
"""The web framework class, handles requests and returns responses.
The primary method from a serving viewpoint is
:meth:`~quart.app.Quart.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.
Attributes:
aborter_class: The class to use to raise HTTP error via the abort
helper function.
app_ctx_globals_class: The class to use for the ``g`` object
asgi_http_class: The class to use to handle the ASGI HTTP
protocol.
asgi_lifespan_class: The class to use to handle the ASGI
lifespan protocol.
asgi_websocket_class: The class to use to handle the ASGI
websocket protocol.
config_class: The class to use for the configuration.
env: The name of the environment the app is running on.
event_class: The class to use to signal an event in an async
manner.
debug: Wrapper around configuration DEBUG value, in many places
this will result in more output if True. If unset, debug
mode will be activated if environ is set to 'development'.
jinja_environment: The class to use for the jinja environment.
jinja_options: The default options to set when creating the jinja
environment.
permanent_session_lifetime: Wrapper around configuration
PERMANENT_SESSION_LIFETIME value. Specifies how long the session
data should survive.
request_class: The class to use for requests.
response_class: The class to user for responses.
secret_key: Warpper around configuration SECRET_KEY value. The app
secret for signing sessions.
session_interface: The class to use as the session interface.
shutdown_event: This event is set when the app starts to
shutdown allowing waiting tasks to know when to stop.
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.
"""
asgi_http_class: type[ASGIHTTPProtocol]
asgi_lifespan_class: type[ASGILifespanProtocol]
asgi_websocket_class: type[ASGIWebsocketProtocol]
shutdown_event: Event
test_app_class: type[TestAppProtocol]
test_client_class: type[TestClientProtocol] # type: ignore[assignment]
aborter_class = Aborter
app_ctx_globals_class = _AppCtxGlobals
asgi_http_class = ASGIHTTPConnection
asgi_lifespan_class = ASGILifespan
asgi_websocket_class = ASGIWebsocketConnection
config_class = Config
event_class = asyncio.Event
jinja_environment = Environment # type: ignore[assignment]
lock_class = asyncio.Lock
request_class = Request
response_class = Response
session_interface = SecureCookieSessionInterface()
test_app_class = TestApp
test_client_class = QuartClient # type: ignore[assignment]
test_cli_runner_class = QuartCliRunner # type: ignore
url_map_class = QuartMap
url_rule_class = QuartRule # type: ignore[assignment]
websocket_class = Websocket
default_config = ImmutableDict(
{
"APPLICATION_ROOT": "/",
"BACKGROUND_TASK_SHUTDOWN_TIMEOUT": 5, # Second
"BODY_TIMEOUT": 60, # Second
"DEBUG": None,
"ENV": None,
"EXPLAIN_TEMPLATE_LOADING": False,
"MAX_CONTENT_LENGTH": 16 * 1024 * 1024, # 16 MB Limit
"MAX_COOKIE_SIZE": 4093,
"PERMANENT_SESSION_LIFETIME": timedelta(days=31),
# Replaces PREFERRED_URL_SCHEME to allow for WebSocket scheme
"PREFER_SECURE_URLS": False,
"PRESERVE_CONTEXT_ON_EXCEPTION": None,
"PROPAGATE_EXCEPTIONS": None,
"RESPONSE_TIMEOUT": 60, # Second
"SECRET_KEY": None,
"SEND_FILE_MAX_AGE_DEFAULT": timedelta(hours=12),
"SERVER_NAME": None,
"SESSION_COOKIE_DOMAIN": None,
"SESSION_COOKIE_HTTPONLY": True,
"SESSION_COOKIE_NAME": "session",
"SESSION_COOKIE_PATH": None,
"SESSION_COOKIE_SAMESITE": None,
"SESSION_COOKIE_SECURE": False,
"SESSION_REFRESH_EACH_REQUEST": True,
"TEMPLATES_AUTO_RELOAD": None,
"TESTING": False,
"TRAP_BAD_REQUEST_ERRORS": None,
"TRAP_HTTP_EXCEPTIONS": False,
}
)
def __init__(
self,
import_name: str,
static_url_path: str | None = None,
static_folder: str | None = "static",
static_host: str | None = None,
host_matching: bool = False,
subdomain_matching: bool = False,
template_folder: str | None = "templates",
instance_path: str | None = None,
instance_relative_config: bool = False,
root_path: str | None = None,
) -> None:
"""Construct a Quart web application.
Use to create a new web application to which requests should
be handled, as specified by the various attached url
rules. See also :class:`~quart.static.PackageStatic` for
additional constructor arguments.
Arguments:
import_name: The name at import of the application, use
``__name__`` unless there is a specific issue.
host_matching: Optionally choose to match the host to the
configured host on request (404 if no match).
instance_path: Optional path to an instance folder, for
deployment specific settings and files.
instance_relative_config: If True load the config from a
path relative to the instance path.
Attributes:
after_request_funcs: The functions to execute after a
request has been handled.
after_websocket_funcs: The functions to execute after a
websocket has been handled.
before_request_funcs: The functions to execute before handling
a request.
before_websocket_funcs: The functions to execute before handling
a websocket.
"""
super().__init__(
import_name,
static_url_path,
static_folder,
static_host,
host_matching,
subdomain_matching,
template_folder,
instance_path,
instance_relative_config,
root_path,
)
self.after_serving_funcs: list[Callable[[], Awaitable[None]]] = []
self.after_websocket_funcs: dict[AppOrBlueprintKey, list[AfterWebsocketCallable]] = (
defaultdict(list)
)
self.background_tasks: WeakSet[asyncio.Task] = WeakSet()
self.before_serving_funcs: list[Callable[[], Awaitable[None]]] = []
self.before_websocket_funcs: dict[AppOrBlueprintKey, list[BeforeWebsocketCallable]] = (
defaultdict(list)
)
self.teardown_websocket_funcs: dict[AppOrBlueprintKey, list[TeardownCallable]] = (
defaultdict(list)
)
self.while_serving_gens: list[AsyncGenerator[None, None]] = []
self.template_context_processors[None] = [_default_template_ctx_processor]
self.cli = AppGroup()
self.cli.name = self.name
if self.has_static_folder:
assert (
bool(static_host) == host_matching
), "Invalid static_host/host_matching combination"
self.add_url_rule(
f"{self.static_url_path}/<path:filename>",
"static",
self.send_static_file,
host=static_host,
)
def get_send_file_max_age(self, filename: str | None) -> int | None:
"""Used by :func:`send_file` to determine the ``max_age`` cache
value for a given file path if it wasn't passed.
By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
the configuration of :data:`~flask.current_app`. This defaults
to ``None``, which tells the browser to use conditional requests
instead of a timed cache, which is usually preferable.
Note this is a duplicate of the same method in the Quart
class.
"""
value = self.config["SEND_FILE_MAX_AGE_DEFAULT"]
if value is None:
return None
if isinstance(value, timedelta):
return int(value.total_seconds())
return value
return None
async def send_static_file(self, filename: str) -> Response:
if not self.has_static_folder:
raise RuntimeError("No static folder for this object")
return await send_from_directory(self.static_folder, filename)
async def open_resource(
self,
path: FilePath,
mode: str = "rb",
) -> AiofilesContextManager[None, None, AsyncBufferedReader]:
"""Open a file for reading.
Use as
.. code-block:: python
async with await app.open_resource(path) as file_:
await file_.read()
"""
if mode not in {"r", "rb", "rt"}:
raise ValueError("Files can only be opened for reading")
return async_open(os.path.join(self.root_path, path), mode) # type: ignore
async def open_instance_resource(
self, path: FilePath, mode: str = "rb"
) -> AiofilesContextManager[None, None, AsyncBufferedReader]:
"""Open a file for reading.
Use as
.. code-block:: python
async with await app.open_instance_resource(path) as file_:
await file_.read()
"""
return async_open(self.instance_path / file_path_to_path(path), mode) # type: ignore
def create_jinja_environment(self) -> Environment: # type: ignore
"""Create and return the jinja environment.
This will create the environment based on the
:attr:`jinja_options` and configuration settings. The
environment will include the Quart globals by default.
"""
options = dict(self.jinja_options)
if "autoescape" not in options:
options["autoescape"] = self.select_jinja_autoescape
if "auto_reload" not in options:
options["auto_reload"] = self.config["TEMPLATES_AUTO_RELOAD"]
jinja_env = self.jinja_environment(self, **options) # type: ignore
jinja_env.globals.update(
{
"config": self.config,
"g": g,
"get_flashed_messages": get_flashed_messages,
"request": request,
"session": session,
"url_for": self.url_for,
}
)
jinja_env.policies["json.dumps_function"] = self.json.dumps
return jinja_env
async def update_template_context(self, context: dict) -> None:
"""Update the provided template context.
This adds additional context from the various template context
processors.
Arguments:
context: The context to update (mutate).
"""
names = [None]
if has_request_context():
names.extend(reversed(request_ctx.request.blueprints)) # type: ignore
elif has_websocket_context():
names.extend(reversed(websocket_ctx.websocket.blueprints)) # type: ignore
extra_context: dict = {}
for name in names:
for processor in self.template_context_processors[name]:
extra_context.update(await self.ensure_async(processor)()) # type: ignore
original = context.copy()
context.update(extra_context)
context.update(original)
@setupmethod
def before_serving(
self,
func: T_before_serving,
) -> T_before_serving:
"""Add a before serving function.
This will allow the function provided to be called once before
anything is served (before any byte is received).
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.before_serving
async def func():
...
Arguments:
func: The function itself.
"""
self.before_serving_funcs.append(func)
return func
@setupmethod
def while_serving(
self,
func: T_while_serving,
) -> T_while_serving:
"""Add a while serving generator function.
This will allow the generator provided to be invoked at
startup and then again at shutdown.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.while_serving
async def func():
... # Startup
yield
... # Shutdown
Arguments:
func: The function itself.
"""
self.while_serving_gens.append(func())
return func
@setupmethod
def after_serving(
self,
func: T_after_serving,
) -> T_after_serving:
"""Add a after serving function.
This will allow the function provided to be called once after
anything is served (after last byte is sent).
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.after_serving
async def func():
...
Arguments:
func: The function itself.
"""
self.after_serving_funcs.append(func)
return func
def create_url_adapter(self, request: BaseRequestWebsocket | None) -> MapAdapter | None:
"""Create and return a URL adapter.
This will create the adapter based on the request if present
otherwise the app configuration.
"""
if request is not None:
subdomain = (
(self.url_map.default_subdomain or None) if not self.subdomain_matching else None
)
return self.url_map.bind_to_request( # type: ignore[attr-defined]
request, subdomain, self.config["SERVER_NAME"]
)
if self.config["SERVER_NAME"] is not None:
scheme = "https" if self.config["PREFER_SECURE_URLS"] else "http"
return self.url_map.bind(self.config["SERVER_NAME"], url_scheme=scheme)
return None
def websocket(
self,
rule: str,
**options: Any,
) -> Callable[[T_websocket], T_websocket]:
"""Add a websocket to the application.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.websocket('/')
async def websocket_route():
...
Arguments:
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``,
.. code-block:: python
@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).
"""
def decorator(func: T_websocket) -> T_websocket:
endpoint = options.pop("endpoint", None)
self.add_websocket(
rule,
endpoint,
func,
**options,
)
return func
return decorator
def add_websocket(
self,
rule: str,
endpoint: str | None = None,
view_func: WebsocketCallable | None = None,
**options: Any,
) -> None:
"""Add a websocket url rule to the application.
This is designed to be used on the application directly. An
example usage,
.. code-block:: python
def websocket_route():
...
app.add_websocket('/', websocket_route)
Arguments:
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``,
.. code-block:: python
@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).
"""
return self.add_url_rule(
rule,
endpoint,
view_func,
methods={"GET"},
websocket=True,
**options,
)
def url_for(
self,
endpoint: str,
*,
_anchor: str | None = None,
_external: bool | None = None,
_method: str | None = None,
_scheme: str | None = None,
**values: Any,
) -> str:
"""Return the url for a specific endpoint.
This is most useful in templates and redirects to create a URL
that can be used in the browser.
Arguments:
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.
"""
app_context = _cv_app.get(None)
request_context = _cv_request.get(None)
websocket_context = _cv_websocket.get(None)
if request_context is not None:
url_adapter = request_context.url_adapter
if endpoint.startswith("."):
if request.blueprint is not None:
endpoint = request.blueprint + endpoint
else:
endpoint = endpoint[1:]
if _external is None:
_external = _scheme is not None
elif websocket_context is not None:
url_adapter = websocket_context.url_adapter
if endpoint.startswith("."):
if websocket.blueprint is not None:
endpoint = websocket.blueprint + endpoint
else:
endpoint = endpoint[1:]
if _external is None:
_external = _scheme is not None
elif app_context is not None:
url_adapter = app_context.url_adapter
if _external is None:
_external = True
else:
url_adapter = self.create_url_adapter(None)
if _external is None:
_external = True
if url_adapter is None:
raise RuntimeError(
"Unable to create a url adapter, try setting the SERVER_NAME config variable."
)
if _scheme is not None and not _external:
raise ValueError("External must be True for scheme usage")
self.inject_url_defaults(endpoint, values)
old_scheme = None
if _scheme is not None:
old_scheme = url_adapter.url_scheme
url_adapter.url_scheme = _scheme
try:
url = url_adapter.build(endpoint, values, method=_method, force_external=_external)
except BuildError as error:
return self.handle_url_build_error(error, endpoint, values)
finally:
if old_scheme is not None:
url_adapter.url_scheme = old_scheme
if _anchor is not None:
quoted_anchor = quote(_anchor, safe="%!#$&'()*+,/:;=?@")
url = f"{url}#{quoted_anchor}"
return url
def make_shell_context(self) -> dict:
"""Create a context for interactive shell usage.
The :attr:`shell_context_processors` can be used to add
additional context.
"""
context = {"app": self, "g": g}
for processor in self.shell_context_processors:
context.update(processor())
return context
def run(
self,
host: str | None = None,
port: int | None = None,
debug: bool | None = None,
use_reloader: bool = True,
loop: asyncio.AbstractEventLoop | None = None,
ca_certs: str | None = None,
certfile: str | None = None,
keyfile: str | None = None,
**kwargs: Any,
) -> None:
"""Run this application.
This is best used for development only, see Hypercorn for
production servers.
Arguments:
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.
"""
if kwargs:
warnings.warn(
f"Additional arguments, {','.join(kwargs.keys())}, are not supported.\n"
"They may be supported by Hypercorn, which is the ASGI server Quart "
"uses by default. This method is meant for development and debugging.",
stacklevel=2,
)
if loop is None:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
if "QUART_DEBUG" in os.environ:
self.debug = get_debug_flag()
if debug is not None:
self.debug = debug
loop.set_debug(self.debug)
shutdown_event = asyncio.Event()
def _signal_handler(*_: Any) -> None:
shutdown_event.set()
for signal_name in {"SIGINT", "SIGTERM", "SIGBREAK"}:
if hasattr(signal, signal_name):
try:
loop.add_signal_handler(getattr(signal, signal_name), _signal_handler)
except NotImplementedError:
# Add signal handler may not be implemented on Windows
signal.signal(getattr(signal, signal_name), _signal_handler)
server_name = self.config.get("SERVER_NAME")
sn_host = None
sn_port = None
if server_name is not None:
sn_host, _, sn_port = server_name.partition(":")
if host is None:
host = sn_host or "127.0.0.1"
if port is None:
port = int(sn_port or "5000")
task = self.run_task(
host,
port,
debug,
ca_certs,
certfile,
keyfile,
shutdown_trigger=shutdown_event.wait, # type: ignore
)
print(f" * Serving Quart app '{self.name}'") # noqa: T201
print(f" * Debug mode: {self.debug or False}") # noqa: T201
print(" * Please use an ASGI server (e.g. Hypercorn) directly in production") # noqa: T201
scheme = "https" if certfile is not None and keyfile is not None else "http"
print(f" * Running on {scheme}://{host}:{port} (CTRL + C to quit)") # noqa: T201
tasks = [loop.create_task(task)]
if use_reloader:
tasks.append(loop.create_task(observe_changes(asyncio.sleep, shutdown_event)))
reload_ = False
try:
loop.run_until_complete(asyncio.gather(*tasks))
except MustReloadError:
reload_ = True
finally:
try:
_cancel_all_tasks(loop)
loop.run_until_complete(loop.shutdown_asyncgens())
finally:
asyncio.set_event_loop(None)
loop.close()
if reload_:
restart()
def run_task(
self,
host: str = "127.0.0.1",
port: int = 5000,
debug: bool | None = None,
ca_certs: str | None = None,
certfile: str | None = None,
keyfile: str | None = None,
shutdown_trigger: Callable[..., Awaitable[None]] | None = None,
) -> Coroutine[None, None, None]:
"""Return a task that when awaited runs this application.
This is best used for development only, see Hypercorn for
production servers.
Arguments:
host: Hostname to listen on. By default this is loopback
only, use 0.0.0.0 to have the server listen externally.
port: Port number to listen on.
debug: If set enable (or disable) debug mode and debug output.
ca_certs: Path to the SSL CA certificate file.
certfile: Path to the SSL certificate file.
keyfile: Path to the SSL key file.
"""
config = HyperConfig()
config.access_log_format = "%(h)s %(r)s %(s)s %(b)s %(D)s"
config.accesslog = "-"
config.bind = [f"{host}:{port}"]
config.ca_certs = ca_certs
config.certfile = certfile
if debug is not None:
self.debug = debug
config.errorlog = config.accesslog
config.keyfile = keyfile
return serve(self, config, shutdown_trigger=shutdown_trigger)
def test_client(self, use_cookies: bool = True, **kwargs: Any) -> TestClientProtocol:
"""Creates and returns a test client."""
return self.test_client_class(self, use_cookies=use_cookies, **kwargs)
def test_cli_runner(self, **kwargs: Any) -> QuartCliRunner:
"""Creates and returns a CLI test runner."""
return self.test_cli_runner_class(self, **kwargs) # type: ignore
@setupmethod
def before_websocket(
self,
func: T_before_websocket,
) -> T_before_websocket:
"""Add a before websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.before_websocket
async def func():
...
Arguments:
func: The before websocket function itself.
"""
self.before_websocket_funcs[None].append(func)
return func
@setupmethod
def after_websocket(
self,
func: T_after_websocket,
) -> T_after_websocket:
"""Add an after websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.after_websocket
async def func(response):
return response
Arguments:
func: The after websocket function itself.
"""
self.after_websocket_funcs[None].append(func)
return func
@setupmethod
def teardown_websocket(
self,
func: T_teardown,
) -> T_teardown:
"""Add a teardown websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.teardown_websocket
async def func():
...
Arguments:
func: The teardown websocket function itself.
"""
self.teardown_websocket_funcs[None].append(func)
return func
async def handle_http_exception(
self, error: HTTPException
) -> HTTPException | ResponseReturnValue:
"""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.
"""
if error.code is None:
return error
if isinstance(error, RoutingException):
return error
blueprints = []
if has_request_context():
blueprints = request.blueprints
elif has_websocket_context():
blueprints = websocket.blueprints
handler = self._find_error_handler(error, blueprints)
if handler is None:
return error
else:
return await self.ensure_async(handler)(error) # type: ignore
async def handle_user_exception(self, error: Exception) -> HTTPException | ResponseReturnValue:
"""Handle an exception that has been raised.
This should forward :class:`~quart.exception.HTTPException` to
:meth:`handle_http_exception`, then attempt to handle the
error. If it cannot it should reraise the error.
"""
if isinstance(error, BadRequestKeyError) and (
self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]
):
error.show_exception = True
if isinstance(error, HTTPException) and not self.trap_http_exception(error):
return await self.handle_http_exception(error)
blueprints = []
if has_request_context():
blueprints = request.blueprints
elif has_websocket_context():
blueprints = websocket.blueprints
handler = self._find_error_handler(error, blueprints)
if handler is None:
raise error
return await self.ensure_async(handler)(error) # type: ignore
async def handle_exception(self, error: Exception) -> ResponseTypes:
"""Handle an uncaught exception.
By default this switches the error response to a 500 internal
server error.
"""
exc_info = sys.exc_info()
await got_request_exception.send_async(
self, _sync_wrapper=self.ensure_async, exception=error
)
propagate = self.config["PROPAGATE_EXCEPTIONS"]
if propagate is None:
propagate = self.testing or self.debug
if propagate:
# Re-raise if called with an active exception, otherwise
# raise the passed in exception.
if exc_info[1] is error:
raise
raise error
self.log_exception(exc_info)
server_error: InternalServerError | ResponseReturnValue
server_error = InternalServerError(original_exception=error)
handler = self._find_error_handler(server_error, request.blueprints)
if handler is not None:
server_error = await self.ensure_async(handler)(server_error) # type: ignore
return await self.finalize_request(server_error, from_error_handler=True)
async def handle_websocket_exception(self, error: Exception) -> ResponseTypes | None:
"""Handle an uncaught exception.
By default this logs the exception and then re-raises it.
"""
exc_info = sys.exc_info()
await got_websocket_exception.send_async(
self, _sync_wrapper=self.ensure_async, exception=error
)
propagate = self.config["PROPAGATE_EXCEPTIONS"]
if propagate is None:
propagate = self.testing or self.debug
if propagate:
# Re-raise if called with an active exception, otherwise
# raise the passed in exception.
if exc_info[1] is error:
raise
raise error
self.log_exception(exc_info)
server_error: InternalServerError | ResponseReturnValue
server_error = InternalServerError(original_exception=error)
handler = self._find_error_handler(server_error, websocket.blueprints)
if handler is not None:
server_error = await self.ensure_async(handler)(server_error) # type: ignore
return await self.finalize_websocket(server_error, from_error_handler=True)
def log_exception(
self,
exception_info: tuple[type, BaseException, TracebackType] | tuple[None, None, None],
) -> None:
"""Log a exception to the :attr:`logger`.
By default this is only invoked for unhandled exceptions.
"""
if has_request_context():
request_ = request_ctx.request
self.logger.error(
f"Exception on request {request_.method} {request_.path}", exc_info=exception_info
)
elif has_websocket_context():
websocket_ = websocket_ctx.websocket
self.logger.error(f"Exception on websocket {websocket_.path}", exc_info=exception_info)
else:
self.logger.error("Exception", exc_info=exception_info)
@overload
def ensure_async(self, func: Callable[P, Awaitable[T]]) -> Callable[P, Awaitable[T]]: ...
@overload
def ensure_async(self, func: Callable[P, T]) -> Callable[P, Awaitable[T]]: ...
def ensure_async(
self, func: Union[Callable[P, Awaitable[T]], Callable[P, T]]
) -> Callable[P, Awaitable[T]]:
"""Ensure that the returned func is async and calls the func.
.. versionadded:: 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.
"""
if asyncio.iscoroutinefunction(func):
return func
else:
return self.sync_to_async(cast(Callable[P, T], func))
def sync_to_async(self, func: Callable[P, T]) -> Callable[P, Awaitable[T]]:
"""Return a async function that will run the synchronous function *func*.
This can be used as so,::
result = await app.sync_to_async(func)(*args, **kwargs)
Override this method to change how the app converts sync code
to be asynchronously callable.
"""
return run_sync(func)
async def do_teardown_request(
self, exc: BaseException | None, request_context: RequestContext | None = None
) -> None:
"""Teardown the request, calling the teardown functions.
Arguments:
exc: Any exception not handled that has caused the request
to teardown.
request_context: The request context, optional as Flask
omits this argument.
"""
names = [*(request_context or request_ctx).request.blueprints, None]
for name in names:
for function in reversed(self.teardown_request_funcs[name]):
await self.ensure_async(function)(exc)
await request_tearing_down.send_async(self, _sync_wrapper=self.ensure_async, exc=exc)
async def do_teardown_websocket(
self, exc: BaseException | None, websocket_context: WebsocketContext | None = None
) -> None:
"""Teardown the websocket, calling the teardown functions.
Arguments:
exc: Any exception not handled that has caused the websocket
to teardown.
websocket_context: The websocket context, optional as Flask
omits this argument.
"""
names = [*(websocket_context or websocket_ctx).websocket.blueprints, None]
for name in names:
for function in reversed(self.teardown_websocket_funcs[name]):
await self.ensure_async(function)(exc)
await websocket_tearing_down.send_async(self, _sync_wrapper=self.ensure_async, exc=exc)
async def do_teardown_appcontext(self, exc: BaseException | None) -> None:
"""Teardown the app (context), calling the teardown functions."""
for function in self.teardown_appcontext_funcs:
await self.ensure_async(function)(exc)
await appcontext_tearing_down.send_async(self, _sync_wrapper=self.ensure_async, exc=exc)
def app_context(self) -> AppContext:
"""Create and return an app context.
This is best used within a context, i.e.
.. code-block:: python
async with app.app_context():
...
"""
return AppContext(self)
def request_context(self, request: Request) -> RequestContext:
"""Create and return a request context.
Use the :meth:`test_request_context` whilst testing. This is
best used within a context, i.e.
.. code-block:: python
async with app.request_context(request):
...
Arguments:
request: A request to build a context around.
"""
return RequestContext(self, request)
def websocket_context(self, websocket: Websocket) -> WebsocketContext:
"""Create and return a websocket context.
Use the :meth:`test_websocket_context` whilst testing. This is
best used within a context, i.e.
.. code-block:: python
async with app.websocket_context(websocket):
...
Arguments:
websocket: A websocket to build a context around.
"""
return WebsocketContext(self, websocket)
def test_app(self) -> TestAppProtocol:
return self.test_app_class(self)
def test_request_context(
self,
path: str,
*,
method: str = "GET",
headers: dict | Headers | None = None,
query_string: dict | None = None,
scheme: str = "http",
send_push_promise: Callable[[str, Headers], Awaitable[None]] = no_op_push,
data: AnyStr | None = None,
form: dict | None = None,
json: Any = sentinel,
root_path: str = "",
http_version: str = "1.1",
scope_base: dict | None = None,
auth: Authorization | tuple[str, str] | None = None,
subdomain: str | None = None,
) -> RequestContext:
"""Create a request context for testing purposes.
This is best used for testing code within request contexts. It
is a simplified wrapper of :meth:`request_context`. It is best
used in a with block, i.e.
.. code-block:: python
async with app.test_request_context("/", method="GET"):
...
Arguments:
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.
"""
headers, path, query_string_bytes = make_test_headers_path_and_query_string(
self,
path,
headers,
query_string,
auth,
subdomain,
)
request_body, body_headers = make_test_body_with_headers(data=data, form=form, json=json)
headers.update(**body_headers)
scope = make_test_scope(
"http",
path,
method,
headers,
query_string_bytes,
scheme,
root_path,
http_version,
scope_base,
)
request = self.request_class(
method,
scheme,
path,
query_string_bytes,
headers,
root_path,
http_version,
send_push_promise=send_push_promise,
scope=scope,
)
request.body.set_result(request_body)
return self.request_context(request)
def add_background_task(self, func: Callable, *args: Any, **kwargs: Any) -> None:
async def _wrapper() -> None:
try:
async with self.app_context():
await self.ensure_async(func)(*args, **kwargs)
except Exception as error:
await self.handle_background_exception(error)
task = asyncio.get_event_loop().create_task(_wrapper())
self.background_tasks.add(task)
async def handle_background_exception(self, error: Exception) -> None:
await got_background_exception.send_async(
self, _sync_wrapper=self.ensure_async, exception=error
)
self.log_exception(sys.exc_info())
async def make_default_options_response(self) -> Response:
"""This is the default route function for OPTIONS requests."""
methods = request_ctx.url_adapter.allowed_methods()
return self.response_class("", headers={"Allow": ", ".join(methods)})
async def make_response(self, result: ResponseReturnValue | HTTPException) -> ResponseTypes:
"""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.
"""
headers: HeadersValue | None = None
status: StatusCode | None = None
if isinstance(result, tuple):
if len(result) == 3:
value, status, headers = result
elif len(result) == 2:
value, status_or_headers = result
if isinstance(status_or_headers, (Headers, dict, list)):
headers = status_or_headers
status = None
elif status_or_headers is not None:
status = status_or_headers # type: ignore[assignment]
else:
raise TypeError(
"""The response value returned must be either (body, status), (body,
headers), or (body, status, headers)"""
)
else:
value = result # type: ignore[assignment]
if value is None:
raise TypeError("The response value returned by the view function cannot be None")
response: ResponseTypes
if isinstance(value, HTTPException):
response = value.get_response() # type: ignore
elif not isinstance(value, (Response, WerkzeugResponse)):
if (
isinstance(value, (str, bytes, bytearray))
or isgenerator(value)
or isasyncgen(value)
):
response = self.response_class(value)
elif isinstance(value, (list, dict)):
response = self.json.response(value) # type: ignore[assignment]
else:
raise TypeError(f"The response value type ({type(value).__name__}) is not valid")
else:
response = value
if status is not None:
response.status_code = int(status)
if headers is not None:
response.headers.update(headers) # type: ignore[arg-type]
return response
async def handle_request(self, request: Request) -> ResponseTypes:
async with self.request_context(request) as request_context:
try:
return await self.full_dispatch_request(request_context)
except asyncio.CancelledError:
raise # CancelledErrors should be handled by serving code.
except Exception as error:
return await self.handle_exception(error)
finally:
if request.scope.get("_quart._preserve_context", False):
self._preserved_context = request_context.copy()
async def handle_websocket(self, websocket: Websocket) -> ResponseTypes | None:
async with self.websocket_context(websocket) as websocket_context:
try:
return await self.full_dispatch_websocket(websocket_context)
except asyncio.CancelledError:
raise # CancelledErrors should be handled by serving code.
except Exception as error:
return await self.handle_websocket_exception(error)
finally:
if websocket.scope.get("_quart._preserve_context", False):
self._preserved_context = websocket_context.copy()
async def full_dispatch_request(
self, request_context: RequestContext | None = None
) -> ResponseTypes:
"""Adds pre and post processing to the request dispatching.
Arguments:
request_context: The request context, optional as Flask
omits this argument.
"""
try:
await request_started.send_async(self, _sync_wrapper=self.ensure_async)
result: ResponseReturnValue | HTTPException | None
result = await self.preprocess_request(request_context)
if result is None:
result = await self.dispatch_request(request_context)
except Exception as error:
result = await self.handle_user_exception(error)
return await self.finalize_request(result, request_context)
async def full_dispatch_websocket(
self, websocket_context: WebsocketContext | None = None
) -> ResponseTypes | None:
"""Adds pre and post processing to the websocket dispatching.
Arguments:
websocket_context: The websocket context, optional to match
the Flask convention.
"""
try:
await websocket_started.send_async(self, _sync_wrapper=self.ensure_async)
result: ResponseReturnValue | HTTPException | None
result = await self.preprocess_websocket(websocket_context)
if result is None:
result = await self.dispatch_websocket(websocket_context)
except Exception as error:
result = await self.handle_user_exception(error)
return await self.finalize_websocket(result, websocket_context)
async def preprocess_request(
self, request_context: RequestContext | None = None
) -> ResponseReturnValue | None:
"""Preprocess the request i.e. call before_request functions.
Arguments:
request_context: The request context, optional as Flask
omits this argument.
"""
names = [None, *reversed((request_context or request_ctx).request.blueprints)]
for name in names:
for processor in self.url_value_preprocessors[name]:
processor(request.endpoint, request.view_args)
for name in names:
for function in self.before_request_funcs[name]:
result = await self.ensure_async(function)()
if result is not None:
return result # type: ignore
return None
async def preprocess_websocket(
self, websocket_context: WebsocketContext | None = None
) -> ResponseReturnValue | None:
"""Preprocess the websocket i.e. call before_websocket functions.
Arguments:
websocket_context: The websocket context, optional as Flask
omits this argument.
"""
names = [
None,
*reversed((websocket_context or websocket_ctx).websocket.blueprints),
]
for name in names:
for processor in self.url_value_preprocessors[name]:
processor(request.endpoint, request.view_args)
for name in names:
for function in self.before_websocket_funcs[name]:
result = await self.ensure_async(function)()
if result is not None:
return result # type: ignore
return None
def raise_routing_exception(self, request: BaseRequestWebsocket) -> NoReturn:
raise request.routing_exception
async def dispatch_request(
self, request_context: RequestContext | None = None
) -> ResponseReturnValue:
"""Dispatch the request to the view function.
Arguments:
request_context: The request context, optional as Flask
omits this argument.
"""
request_ = (request_context or request_ctx).request
if request_.routing_exception is not None:
self.raise_routing_exception(request_)
if request_.method == "OPTIONS" and request_.url_rule.provide_automatic_options:
return await self.make_default_options_response()
handler = self.view_functions[request_.url_rule.endpoint]
return await self.ensure_async(handler)(**request_.view_args) # type: ignore
async def dispatch_websocket(
self, websocket_context: WebsocketContext | None = None
) -> ResponseReturnValue | None:
"""Dispatch the websocket to the view function.
Arguments:
websocket_context: The websocket context, optional to match
the Flask convention.
"""
websocket_ = (websocket_context or websocket_ctx).websocket
if websocket_.routing_exception is not None:
self.raise_routing_exception(websocket_)
handler = self.view_functions[websocket_.url_rule.endpoint]
return await self.ensure_async(handler)(**websocket_.view_args) # type: ignore
async def finalize_request(
self,
result: ResponseReturnValue | HTTPException,
request_context: RequestContext | None = None,
from_error_handler: bool = False,
) -> ResponseTypes:
"""Turns the view response return value into a response.
Arguments:
result: The result of the request to finalize into a response.
request_context: The request context, optional as Flask
omits this argument.
"""
response = await self.make_response(result)
try:
response = await self.process_response(response, request_context)
await request_finished.send_async(
self, _sync_wrapper=self.ensure_async, response=response
)
except Exception:
if not from_error_handler:
raise
self.logger.exception("Request finalizing errored")
return response
async def finalize_websocket(
self,
result: ResponseReturnValue | HTTPException,
websocket_context: WebsocketContext | None = None,
from_error_handler: bool = False,
) -> ResponseTypes | None:
"""Turns the view response return value into a response.
Arguments:
result: The result of the websocket to finalize into a response.
websocket_context: The websocket context, optional as Flask
omits this argument.
"""
if result is not None:
response = await self.make_response(result)
else:
response = None
try:
response = await self.postprocess_websocket(response, websocket_context)
await websocket_finished.send_async(
self, _sync_wrapper=self.ensure_async, response=response
)
except Exception:
if not from_error_handler:
raise
self.logger.exception("Request finalizing errored")
return response
async def process_response(
self,
response: ResponseTypes,
request_context: RequestContext | None = None,
) -> ResponseTypes:
"""Postprocess the request acting on the response.
Arguments:
response: The response after the request is finalized.
request_context: The request context, optional as Flask
omits this argument.
"""
names = [*(request_context or request_ctx).request.blueprints, None]
for function in (request_context or request_ctx)._after_request_functions:
response = await self.ensure_async(function)(response) # type: ignore
for name in names:
for function in reversed(self.after_request_funcs[name]):
response = await self.ensure_async(function)(response)
session_ = (request_context or request_ctx).session
if not self.session_interface.is_null_session(session_):
await self.ensure_async(self.session_interface.save_session)(self, session_, response)
return response
async def postprocess_websocket(
self,
response: ResponseTypes | None,
websocket_context: WebsocketContext | None = None,
) -> ResponseTypes:
"""Postprocess the websocket acting on the response.
Arguments:
response: The response after the websocket is finalized.
websocket_context: The websocket context, optional as Flask
omits this argument.
"""
names = [*(websocket_context or websocket_ctx).websocket.blueprints, None]
for function in (websocket_context or websocket_ctx)._after_websocket_functions:
response = await self.ensure_async(function)(response) # type: ignore
for name in names:
for function in reversed(self.after_websocket_funcs[name]):
response = await self.ensure_async(function)(response) # type: ignore
session_ = (websocket_context or websocket_ctx).session
if not self.session_interface.is_null_session(session_):
await self.session_interface.save_session(self, session_, response)
return response
async def __call__(
self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable
) -> None:
"""Called by ASGI servers.
The related :meth:`~quart.app.Quart.asgi_app` is called,
allowing for middleware usage whilst keeping the top level app
a :class:`~quart.app.Quart` instance.
"""
await self.asgi_app(scope, receive, send)
async def asgi_app(
self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable
) -> 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,
.. code-block:: python
app.asgi_app = middleware(app.asgi_app)
"""
asgi_handler: ASGIHTTPProtocol | ASGILifespanProtocol | ASGIWebsocketProtocol
if scope["type"] == "http":
asgi_handler = self.asgi_http_class(self, scope)
elif scope["type"] == "websocket":
asgi_handler = self.asgi_websocket_class(self, scope)
elif scope["type"] == "lifespan":
asgi_handler = self.asgi_lifespan_class(self, scope)
else:
raise RuntimeError("ASGI Scope type is unknown")
await asgi_handler(receive, send)
async def startup(self) -> None:
self.shutdown_event = self.event_class()
try:
async with self.app_context():
for func in self.before_serving_funcs:
await self.ensure_async(func)()
for gen in self.while_serving_gens:
await gen.__anext__()
except Exception as error:
await got_serving_exception.send_async(
self, _sync_wrapper=self.ensure_async, exception=error
)
self.log_exception(sys.exc_info())
raise
async def shutdown(self) -> None:
self.shutdown_event.set()
try:
await asyncio.wait_for(
asyncio.gather(*self.background_tasks),
timeout=self.config["BACKGROUND_TASK_SHUTDOWN_TIMEOUT"],
)
except asyncio.TimeoutError:
await cancel_tasks(self.background_tasks) # type: ignore
try:
async with self.app_context():
for func in self.after_serving_funcs:
await self.ensure_async(func)()
for gen in self.while_serving_gens:
try:
await gen.__anext__()
except StopAsyncIteration:
pass
else:
raise RuntimeError("While serving generator didn't terminate")
except Exception as error:
await got_serving_exception.send_async(
self, _sync_wrapper=self.ensure_async, exception=error
)
self.log_exception(sys.exc_info())
raise
| (import_name: 'str', static_url_path: 'str | None' = None, static_folder: 'str | None' = 'static', static_host: 'str | None' = None, host_matching: 'bool' = False, subdomain_matching: 'bool' = False, template_folder: 'str | None' = 'templates', instance_path: 'str | None' = None, instance_relative_config: 'bool' = False, root_path: 'str | None' = None) -> 'None' |
29,318 | quart.app | __call__ | Called by ASGI servers.
The related :meth:`~quart.app.Quart.asgi_app` is called,
allowing for middleware usage whilst keeping the top level app
a :class:`~quart.app.Quart` instance.
| def raise_routing_exception(self, request: BaseRequestWebsocket) -> NoReturn:
raise request.routing_exception
| (self, 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.HTTPEarlyHintEvent, 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[NoneType]]) -> NoneType |
29,319 | quart.app | __init__ | Construct a Quart web application.
Use to create a new web application to which requests should
be handled, as specified by the various attached url
rules. See also :class:`~quart.static.PackageStatic` for
additional constructor arguments.
Arguments:
import_name: The name at import of the application, use
``__name__`` unless there is a specific issue.
host_matching: Optionally choose to match the host to the
configured host on request (404 if no match).
instance_path: Optional path to an instance folder, for
deployment specific settings and files.
instance_relative_config: If True load the config from a
path relative to the instance path.
Attributes:
after_request_funcs: The functions to execute after a
request has been handled.
after_websocket_funcs: The functions to execute after a
websocket has been handled.
before_request_funcs: The functions to execute before handling
a request.
before_websocket_funcs: The functions to execute before handling
a websocket.
| def __init__(
self,
import_name: str,
static_url_path: str | None = None,
static_folder: str | None = "static",
static_host: str | None = None,
host_matching: bool = False,
subdomain_matching: bool = False,
template_folder: str | None = "templates",
instance_path: str | None = None,
instance_relative_config: bool = False,
root_path: str | None = None,
) -> None:
"""Construct a Quart web application.
Use to create a new web application to which requests should
be handled, as specified by the various attached url
rules. See also :class:`~quart.static.PackageStatic` for
additional constructor arguments.
Arguments:
import_name: The name at import of the application, use
``__name__`` unless there is a specific issue.
host_matching: Optionally choose to match the host to the
configured host on request (404 if no match).
instance_path: Optional path to an instance folder, for
deployment specific settings and files.
instance_relative_config: If True load the config from a
path relative to the instance path.
Attributes:
after_request_funcs: The functions to execute after a
request has been handled.
after_websocket_funcs: The functions to execute after a
websocket has been handled.
before_request_funcs: The functions to execute before handling
a request.
before_websocket_funcs: The functions to execute before handling
a websocket.
"""
super().__init__(
import_name,
static_url_path,
static_folder,
static_host,
host_matching,
subdomain_matching,
template_folder,
instance_path,
instance_relative_config,
root_path,
)
self.after_serving_funcs: list[Callable[[], Awaitable[None]]] = []
self.after_websocket_funcs: dict[AppOrBlueprintKey, list[AfterWebsocketCallable]] = (
defaultdict(list)
)
self.background_tasks: WeakSet[asyncio.Task] = WeakSet()
self.before_serving_funcs: list[Callable[[], Awaitable[None]]] = []
self.before_websocket_funcs: dict[AppOrBlueprintKey, list[BeforeWebsocketCallable]] = (
defaultdict(list)
)
self.teardown_websocket_funcs: dict[AppOrBlueprintKey, list[TeardownCallable]] = (
defaultdict(list)
)
self.while_serving_gens: list[AsyncGenerator[None, None]] = []
self.template_context_processors[None] = [_default_template_ctx_processor]
self.cli = AppGroup()
self.cli.name = self.name
if self.has_static_folder:
assert (
bool(static_host) == host_matching
), "Invalid static_host/host_matching combination"
self.add_url_rule(
f"{self.static_url_path}/<path:filename>",
"static",
self.send_static_file,
host=static_host,
)
| (self, import_name: str, static_url_path: Optional[str] = None, static_folder: str | None = 'static', static_host: Optional[str] = None, host_matching: bool = False, subdomain_matching: bool = False, template_folder: str | None = 'templates', instance_path: Optional[str] = None, instance_relative_config: bool = False, root_path: Optional[str] = None) -> NoneType |
29,322 | flask.sansio.app | _find_error_handler | Return a registered error handler for an exception in this order:
blueprint handler for a specific code, app handler for a specific code,
blueprint handler for an exception class, app handler for an exception
class, or ``None`` if a suitable handler is not found.
| def _find_error_handler(
self, e: Exception, blueprints: list[str]
) -> ft.ErrorHandlerCallable | None:
"""Return a registered error handler for an exception in this order:
blueprint handler for a specific code, app handler for a specific code,
blueprint handler for an exception class, app handler for an exception
class, or ``None`` if a suitable handler is not found.
"""
exc_class, code = self._get_exc_class_and_code(type(e))
names = (*blueprints, None)
for c in (code, None) if code is not None else (None,):
for name in names:
handler_map = self.error_handler_spec[name][c]
if not handler_map:
continue
for cls in exc_class.__mro__:
handler = handler_map.get(cls)
if handler is not None:
return handler
return None
| (self, e: 'Exception', blueprints: 'list[str]') -> 'ft.ErrorHandlerCallable | None' |
29,325 | quart.app | add_background_task | null | def add_background_task(self, func: Callable, *args: Any, **kwargs: Any) -> None:
async def _wrapper() -> None:
try:
async with self.app_context():
await self.ensure_async(func)(*args, **kwargs)
except Exception as error:
await self.handle_background_exception(error)
task = asyncio.get_event_loop().create_task(_wrapper())
self.background_tasks.add(task)
| (self, func: Callable, *args: Any, **kwargs: Any) -> NoneType |
29,326 | flask.sansio.app | add_template_filter | Register a custom template filter. Works exactly like the
:meth:`template_filter` decorator.
:param name: the optional name of the filter, otherwise the
function name will be used.
| from __future__ import annotations
import logging
import os
import sys
import typing as t
from datetime import timedelta
from itertools import chain
from werkzeug.exceptions import Aborter
from werkzeug.exceptions import BadRequest
from werkzeug.exceptions import BadRequestKeyError
from werkzeug.routing import BuildError
from werkzeug.routing import Map
from werkzeug.routing import Rule
from werkzeug.sansio.response import Response
from werkzeug.utils import cached_property
from werkzeug.utils import redirect as _wz_redirect
from .. import typing as ft
from ..config import Config
from ..config import ConfigAttribute
from ..ctx import _AppCtxGlobals
from ..helpers import _split_blueprint_path
from ..helpers import get_debug_flag
from ..json.provider import DefaultJSONProvider
from ..json.provider import JSONProvider
from ..logging import create_logger
from ..templating import DispatchingJinjaLoader
from ..templating import Environment
from .scaffold import _endpoint_from_view_func
from .scaffold import find_package
from .scaffold import Scaffold
from .scaffold import setupmethod
if t.TYPE_CHECKING: # pragma: no cover
from werkzeug.wrappers import Response as BaseResponse
from ..testing import FlaskClient
from ..testing import FlaskCliRunner
from .blueprints import Blueprint
T_shell_context_processor = t.TypeVar(
"T_shell_context_processor", bound=ft.ShellContextProcessorCallable
)
T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)
T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)
T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)
T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)
def _make_timedelta(value: timedelta | int | None) -> timedelta | None:
if value is None or isinstance(value, timedelta):
return value
return timedelta(seconds=value)
| (self, f: Callable[..., Any], name: str | None = None) -> NoneType |
29,327 | flask.sansio.app | add_template_global | Register a custom template global function. Works exactly like the
:meth:`template_global` decorator.
.. versionadded:: 0.10
:param name: the optional name of the global function, otherwise the
function name will be used.
| from __future__ import annotations
import logging
import os
import sys
import typing as t
from datetime import timedelta
from itertools import chain
from werkzeug.exceptions import Aborter
from werkzeug.exceptions import BadRequest
from werkzeug.exceptions import BadRequestKeyError
from werkzeug.routing import BuildError
from werkzeug.routing import Map
from werkzeug.routing import Rule
from werkzeug.sansio.response import Response
from werkzeug.utils import cached_property
from werkzeug.utils import redirect as _wz_redirect
from .. import typing as ft
from ..config import Config
from ..config import ConfigAttribute
from ..ctx import _AppCtxGlobals
from ..helpers import _split_blueprint_path
from ..helpers import get_debug_flag
from ..json.provider import DefaultJSONProvider
from ..json.provider import JSONProvider
from ..logging import create_logger
from ..templating import DispatchingJinjaLoader
from ..templating import Environment
from .scaffold import _endpoint_from_view_func
from .scaffold import find_package
from .scaffold import Scaffold
from .scaffold import setupmethod
if t.TYPE_CHECKING: # pragma: no cover
from werkzeug.wrappers import Response as BaseResponse
from ..testing import FlaskClient
from ..testing import FlaskCliRunner
from .blueprints import Blueprint
T_shell_context_processor = t.TypeVar(
"T_shell_context_processor", bound=ft.ShellContextProcessorCallable
)
T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)
T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)
T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)
T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)
def _make_timedelta(value: timedelta | int | None) -> timedelta | None:
if value is None or isinstance(value, timedelta):
return value
return timedelta(seconds=value)
| (self, f: Callable[..., Any], name: str | None = None) -> NoneType |
29,328 | flask.sansio.app | add_template_test | Register a custom template test. Works exactly like the
:meth:`template_test` decorator.
.. versionadded:: 0.10
:param name: the optional name of the test, otherwise the
function name will be used.
| from __future__ import annotations
import logging
import os
import sys
import typing as t
from datetime import timedelta
from itertools import chain
from werkzeug.exceptions import Aborter
from werkzeug.exceptions import BadRequest
from werkzeug.exceptions import BadRequestKeyError
from werkzeug.routing import BuildError
from werkzeug.routing import Map
from werkzeug.routing import Rule
from werkzeug.sansio.response import Response
from werkzeug.utils import cached_property
from werkzeug.utils import redirect as _wz_redirect
from .. import typing as ft
from ..config import Config
from ..config import ConfigAttribute
from ..ctx import _AppCtxGlobals
from ..helpers import _split_blueprint_path
from ..helpers import get_debug_flag
from ..json.provider import DefaultJSONProvider
from ..json.provider import JSONProvider
from ..logging import create_logger
from ..templating import DispatchingJinjaLoader
from ..templating import Environment
from .scaffold import _endpoint_from_view_func
from .scaffold import find_package
from .scaffold import Scaffold
from .scaffold import setupmethod
if t.TYPE_CHECKING: # pragma: no cover
from werkzeug.wrappers import Response as BaseResponse
from ..testing import FlaskClient
from ..testing import FlaskCliRunner
from .blueprints import Blueprint
T_shell_context_processor = t.TypeVar(
"T_shell_context_processor", bound=ft.ShellContextProcessorCallable
)
T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)
T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)
T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)
T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)
def _make_timedelta(value: timedelta | int | None) -> timedelta | None:
if value is None or isinstance(value, timedelta):
return value
return timedelta(seconds=value)
| (self, f: Callable[..., bool], name: str | None = None) -> NoneType |
29,329 | flask.sansio.app | add_url_rule | null | from __future__ import annotations
import logging
import os
import sys
import typing as t
from datetime import timedelta
from itertools import chain
from werkzeug.exceptions import Aborter
from werkzeug.exceptions import BadRequest
from werkzeug.exceptions import BadRequestKeyError
from werkzeug.routing import BuildError
from werkzeug.routing import Map
from werkzeug.routing import Rule
from werkzeug.sansio.response import Response
from werkzeug.utils import cached_property
from werkzeug.utils import redirect as _wz_redirect
from .. import typing as ft
from ..config import Config
from ..config import ConfigAttribute
from ..ctx import _AppCtxGlobals
from ..helpers import _split_blueprint_path
from ..helpers import get_debug_flag
from ..json.provider import DefaultJSONProvider
from ..json.provider import JSONProvider
from ..logging import create_logger
from ..templating import DispatchingJinjaLoader
from ..templating import Environment
from .scaffold import _endpoint_from_view_func
from .scaffold import find_package
from .scaffold import Scaffold
from .scaffold import setupmethod
if t.TYPE_CHECKING: # pragma: no cover
from werkzeug.wrappers import Response as BaseResponse
from ..testing import FlaskClient
from ..testing import FlaskCliRunner
from .blueprints import Blueprint
T_shell_context_processor = t.TypeVar(
"T_shell_context_processor", bound=ft.ShellContextProcessorCallable
)
T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)
T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)
T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)
T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)
def _make_timedelta(value: timedelta | int | None) -> timedelta | None:
if value is None or isinstance(value, timedelta):
return value
return timedelta(seconds=value)
| (self, rule: 'str', endpoint: 'str | None' = None, view_func: 'ft.RouteCallable | None' = None, provide_automatic_options: 'bool | None' = None, **options: 't.Any') -> 'None' |
29,330 | quart.app | add_websocket | Add a websocket url rule to the application.
This is designed to be used on the application directly. An
example usage,
.. code-block:: python
def websocket_route():
...
app.add_websocket('/', websocket_route)
Arguments:
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``,
.. code-block:: python
@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).
| def add_websocket(
self,
rule: str,
endpoint: str | None = None,
view_func: WebsocketCallable | None = None,
**options: Any,
) -> None:
"""Add a websocket url rule to the application.
This is designed to be used on the application directly. An
example usage,
.. code-block:: python
def websocket_route():
...
app.add_websocket('/', websocket_route)
Arguments:
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``,
.. code-block:: python
@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).
"""
return self.add_url_rule(
rule,
endpoint,
view_func,
methods={"GET"},
websocket=True,
**options,
)
| (self, rule: str, endpoint: Optional[str] = None, view_func: Union[Callable[..., Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], Union[werkzeug.datastructures.headers.Headers, Mapping[str, Union[str, List[str], Tuple[str, ...]]], Sequence[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], int], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], int, Union[werkzeug.datastructures.headers.Headers, Mapping[str, Union[str, List[str], Tuple[str, ...]]], Sequence[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], NoneType]], Callable[..., Awaitable[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], Union[werkzeug.datastructures.headers.Headers, Mapping[str, Union[str, List[str], Tuple[str, ...]]], Sequence[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], int], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], int, Union[werkzeug.datastructures.headers.Headers, Mapping[str, Union[str, List[str], Tuple[str, ...]]], Sequence[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], NoneType]]], NoneType] = None, **options: Any) -> NoneType |
29,332 | quart.app | after_serving | Add a after serving function.
This will allow the function provided to be called once after
anything is served (after last byte is sent).
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.after_serving
async def func():
...
Arguments:
func: The function itself.
| from __future__ import annotations
import asyncio
import os
import signal
import sys
import warnings
from collections import defaultdict
from datetime import timedelta
from inspect import isasyncgen, isgenerator
from types import TracebackType
from typing import (
Any,
AnyStr,
AsyncGenerator,
Awaitable,
Callable,
cast,
Coroutine,
NoReturn,
Optional,
overload,
TypeVar,
Union,
)
from urllib.parse import quote
from weakref import WeakSet
from aiofiles import open as async_open
from aiofiles.base import AiofilesContextManager
from aiofiles.threadpool.binary import AsyncBufferedReader
from flask.sansio.app import App
from flask.sansio.scaffold import setupmethod
from hypercorn.asyncio import serve
from hypercorn.config import Config as HyperConfig
from hypercorn.typing import ASGIReceiveCallable, ASGISendCallable, Scope
from werkzeug.datastructures import Authorization, Headers, ImmutableDict
from werkzeug.exceptions import Aborter, BadRequestKeyError, HTTPException, InternalServerError
from werkzeug.routing import BuildError, MapAdapter, RoutingException
from werkzeug.wrappers import Response as WerkzeugResponse
from .asgi import ASGIHTTPConnection, ASGILifespan, ASGIWebsocketConnection
from .cli import AppGroup
from .config import Config
from .ctx import (
_AppCtxGlobals,
AppContext,
has_request_context,
has_websocket_context,
RequestContext,
WebsocketContext,
)
from .globals import (
_cv_app,
_cv_request,
_cv_websocket,
g,
request,
request_ctx,
session,
websocket,
websocket_ctx,
)
from .helpers import get_debug_flag, get_flashed_messages, send_from_directory
from .routing import QuartMap, QuartRule
from .sessions import SecureCookieSessionInterface
from .signals import (
appcontext_tearing_down,
got_background_exception,
got_request_exception,
got_serving_exception,
got_websocket_exception,
request_finished,
request_started,
request_tearing_down,
websocket_finished,
websocket_started,
websocket_tearing_down,
)
from .templating import _default_template_ctx_processor, Environment
from .testing import (
make_test_body_with_headers,
make_test_headers_path_and_query_string,
make_test_scope,
no_op_push,
QuartClient,
QuartCliRunner,
sentinel,
TestApp,
)
from .typing import (
AfterServingCallable,
AfterWebsocketCallable,
ASGIHTTPProtocol,
ASGILifespanProtocol,
ASGIWebsocketProtocol,
BeforeServingCallable,
BeforeWebsocketCallable,
Event,
FilePath,
HeadersValue,
ResponseReturnValue,
ResponseTypes,
ShellContextProcessorCallable,
StatusCode,
TeardownCallable,
TemplateFilterCallable,
TemplateGlobalCallable,
TemplateTestCallable,
TestAppProtocol,
TestClientProtocol,
WebsocketCallable,
WhileServingCallable,
)
from .utils import (
cancel_tasks,
file_path_to_path,
MustReloadError,
observe_changes,
restart,
run_sync,
)
from .wrappers import BaseRequestWebsocket, Request, Response, Websocket
try:
from typing import ParamSpec
except ImportError:
from typing_extensions import ParamSpec # type: ignore
AppOrBlueprintKey = Optional[str] # The App key is None, whereas blueprints are named
T_after_serving = TypeVar("T_after_serving", bound=AfterServingCallable)
T_after_websocket = TypeVar("T_after_websocket", bound=AfterWebsocketCallable)
T_before_serving = TypeVar("T_before_serving", bound=BeforeServingCallable)
T_before_websocket = TypeVar("T_before_websocket", bound=BeforeWebsocketCallable)
T_shell_context_processor = TypeVar(
"T_shell_context_processor", bound=ShellContextProcessorCallable
)
T_teardown = TypeVar("T_teardown", bound=TeardownCallable)
T_template_filter = TypeVar("T_template_filter", bound=TemplateFilterCallable)
T_template_global = TypeVar("T_template_global", bound=TemplateGlobalCallable)
T_template_test = TypeVar("T_template_test", bound=TemplateTestCallable)
T_websocket = TypeVar("T_websocket", bound=WebsocketCallable)
T_while_serving = TypeVar("T_while_serving", bound=WhileServingCallable)
T = TypeVar("T")
P = ParamSpec("P")
def _make_timedelta(value: timedelta | int | None) -> timedelta | None:
if value is None or isinstance(value, timedelta):
return value
return timedelta(seconds=value)
| (self, func: ~T_after_serving) -> ~T_after_serving |
29,333 | quart.app | after_websocket | Add an after websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.after_websocket
async def func(response):
return response
Arguments:
func: The after websocket function itself.
| from __future__ import annotations
import asyncio
import os
import signal
import sys
import warnings
from collections import defaultdict
from datetime import timedelta
from inspect import isasyncgen, isgenerator
from types import TracebackType
from typing import (
Any,
AnyStr,
AsyncGenerator,
Awaitable,
Callable,
cast,
Coroutine,
NoReturn,
Optional,
overload,
TypeVar,
Union,
)
from urllib.parse import quote
from weakref import WeakSet
from aiofiles import open as async_open
from aiofiles.base import AiofilesContextManager
from aiofiles.threadpool.binary import AsyncBufferedReader
from flask.sansio.app import App
from flask.sansio.scaffold import setupmethod
from hypercorn.asyncio import serve
from hypercorn.config import Config as HyperConfig
from hypercorn.typing import ASGIReceiveCallable, ASGISendCallable, Scope
from werkzeug.datastructures import Authorization, Headers, ImmutableDict
from werkzeug.exceptions import Aborter, BadRequestKeyError, HTTPException, InternalServerError
from werkzeug.routing import BuildError, MapAdapter, RoutingException
from werkzeug.wrappers import Response as WerkzeugResponse
from .asgi import ASGIHTTPConnection, ASGILifespan, ASGIWebsocketConnection
from .cli import AppGroup
from .config import Config
from .ctx import (
_AppCtxGlobals,
AppContext,
has_request_context,
has_websocket_context,
RequestContext,
WebsocketContext,
)
from .globals import (
_cv_app,
_cv_request,
_cv_websocket,
g,
request,
request_ctx,
session,
websocket,
websocket_ctx,
)
from .helpers import get_debug_flag, get_flashed_messages, send_from_directory
from .routing import QuartMap, QuartRule
from .sessions import SecureCookieSessionInterface
from .signals import (
appcontext_tearing_down,
got_background_exception,
got_request_exception,
got_serving_exception,
got_websocket_exception,
request_finished,
request_started,
request_tearing_down,
websocket_finished,
websocket_started,
websocket_tearing_down,
)
from .templating import _default_template_ctx_processor, Environment
from .testing import (
make_test_body_with_headers,
make_test_headers_path_and_query_string,
make_test_scope,
no_op_push,
QuartClient,
QuartCliRunner,
sentinel,
TestApp,
)
from .typing import (
AfterServingCallable,
AfterWebsocketCallable,
ASGIHTTPProtocol,
ASGILifespanProtocol,
ASGIWebsocketProtocol,
BeforeServingCallable,
BeforeWebsocketCallable,
Event,
FilePath,
HeadersValue,
ResponseReturnValue,
ResponseTypes,
ShellContextProcessorCallable,
StatusCode,
TeardownCallable,
TemplateFilterCallable,
TemplateGlobalCallable,
TemplateTestCallable,
TestAppProtocol,
TestClientProtocol,
WebsocketCallable,
WhileServingCallable,
)
from .utils import (
cancel_tasks,
file_path_to_path,
MustReloadError,
observe_changes,
restart,
run_sync,
)
from .wrappers import BaseRequestWebsocket, Request, Response, Websocket
try:
from typing import ParamSpec
except ImportError:
from typing_extensions import ParamSpec # type: ignore
AppOrBlueprintKey = Optional[str] # The App key is None, whereas blueprints are named
T_after_serving = TypeVar("T_after_serving", bound=AfterServingCallable)
T_after_websocket = TypeVar("T_after_websocket", bound=AfterWebsocketCallable)
T_before_serving = TypeVar("T_before_serving", bound=BeforeServingCallable)
T_before_websocket = TypeVar("T_before_websocket", bound=BeforeWebsocketCallable)
T_shell_context_processor = TypeVar(
"T_shell_context_processor", bound=ShellContextProcessorCallable
)
T_teardown = TypeVar("T_teardown", bound=TeardownCallable)
T_template_filter = TypeVar("T_template_filter", bound=TemplateFilterCallable)
T_template_global = TypeVar("T_template_global", bound=TemplateGlobalCallable)
T_template_test = TypeVar("T_template_test", bound=TemplateTestCallable)
T_websocket = TypeVar("T_websocket", bound=WebsocketCallable)
T_while_serving = TypeVar("T_while_serving", bound=WhileServingCallable)
T = TypeVar("T")
P = ParamSpec("P")
def _make_timedelta(value: timedelta | int | None) -> timedelta | None:
if value is None or isinstance(value, timedelta):
return value
return timedelta(seconds=value)
| (self, func: ~T_after_websocket) -> ~T_after_websocket |
29,334 | quart.app | app_context | Create and return an app context.
This is best used within a context, i.e.
.. code-block:: python
async with app.app_context():
...
| def app_context(self) -> AppContext:
"""Create and return an app context.
This is best used within a context, i.e.
.. code-block:: python
async with app.app_context():
...
"""
return AppContext(self)
| (self) -> quart.ctx.AppContext |
29,335 | quart.app | asgi_app | 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,
.. code-block:: python
app.asgi_app = middleware(app.asgi_app)
| def raise_routing_exception(self, request: BaseRequestWebsocket) -> NoReturn:
raise request.routing_exception
| (self, 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.HTTPEarlyHintEvent, 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[NoneType]]) -> NoneType |
29,338 | quart.app | before_serving | Add a before serving function.
This will allow the function provided to be called once before
anything is served (before any byte is received).
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.before_serving
async def func():
...
Arguments:
func: The function itself.
| from __future__ import annotations
import asyncio
import os
import signal
import sys
import warnings
from collections import defaultdict
from datetime import timedelta
from inspect import isasyncgen, isgenerator
from types import TracebackType
from typing import (
Any,
AnyStr,
AsyncGenerator,
Awaitable,
Callable,
cast,
Coroutine,
NoReturn,
Optional,
overload,
TypeVar,
Union,
)
from urllib.parse import quote
from weakref import WeakSet
from aiofiles import open as async_open
from aiofiles.base import AiofilesContextManager
from aiofiles.threadpool.binary import AsyncBufferedReader
from flask.sansio.app import App
from flask.sansio.scaffold import setupmethod
from hypercorn.asyncio import serve
from hypercorn.config import Config as HyperConfig
from hypercorn.typing import ASGIReceiveCallable, ASGISendCallable, Scope
from werkzeug.datastructures import Authorization, Headers, ImmutableDict
from werkzeug.exceptions import Aborter, BadRequestKeyError, HTTPException, InternalServerError
from werkzeug.routing import BuildError, MapAdapter, RoutingException
from werkzeug.wrappers import Response as WerkzeugResponse
from .asgi import ASGIHTTPConnection, ASGILifespan, ASGIWebsocketConnection
from .cli import AppGroup
from .config import Config
from .ctx import (
_AppCtxGlobals,
AppContext,
has_request_context,
has_websocket_context,
RequestContext,
WebsocketContext,
)
from .globals import (
_cv_app,
_cv_request,
_cv_websocket,
g,
request,
request_ctx,
session,
websocket,
websocket_ctx,
)
from .helpers import get_debug_flag, get_flashed_messages, send_from_directory
from .routing import QuartMap, QuartRule
from .sessions import SecureCookieSessionInterface
from .signals import (
appcontext_tearing_down,
got_background_exception,
got_request_exception,
got_serving_exception,
got_websocket_exception,
request_finished,
request_started,
request_tearing_down,
websocket_finished,
websocket_started,
websocket_tearing_down,
)
from .templating import _default_template_ctx_processor, Environment
from .testing import (
make_test_body_with_headers,
make_test_headers_path_and_query_string,
make_test_scope,
no_op_push,
QuartClient,
QuartCliRunner,
sentinel,
TestApp,
)
from .typing import (
AfterServingCallable,
AfterWebsocketCallable,
ASGIHTTPProtocol,
ASGILifespanProtocol,
ASGIWebsocketProtocol,
BeforeServingCallable,
BeforeWebsocketCallable,
Event,
FilePath,
HeadersValue,
ResponseReturnValue,
ResponseTypes,
ShellContextProcessorCallable,
StatusCode,
TeardownCallable,
TemplateFilterCallable,
TemplateGlobalCallable,
TemplateTestCallable,
TestAppProtocol,
TestClientProtocol,
WebsocketCallable,
WhileServingCallable,
)
from .utils import (
cancel_tasks,
file_path_to_path,
MustReloadError,
observe_changes,
restart,
run_sync,
)
from .wrappers import BaseRequestWebsocket, Request, Response, Websocket
try:
from typing import ParamSpec
except ImportError:
from typing_extensions import ParamSpec # type: ignore
AppOrBlueprintKey = Optional[str] # The App key is None, whereas blueprints are named
T_after_serving = TypeVar("T_after_serving", bound=AfterServingCallable)
T_after_websocket = TypeVar("T_after_websocket", bound=AfterWebsocketCallable)
T_before_serving = TypeVar("T_before_serving", bound=BeforeServingCallable)
T_before_websocket = TypeVar("T_before_websocket", bound=BeforeWebsocketCallable)
T_shell_context_processor = TypeVar(
"T_shell_context_processor", bound=ShellContextProcessorCallable
)
T_teardown = TypeVar("T_teardown", bound=TeardownCallable)
T_template_filter = TypeVar("T_template_filter", bound=TemplateFilterCallable)
T_template_global = TypeVar("T_template_global", bound=TemplateGlobalCallable)
T_template_test = TypeVar("T_template_test", bound=TemplateTestCallable)
T_websocket = TypeVar("T_websocket", bound=WebsocketCallable)
T_while_serving = TypeVar("T_while_serving", bound=WhileServingCallable)
T = TypeVar("T")
P = ParamSpec("P")
def _make_timedelta(value: timedelta | int | None) -> timedelta | None:
if value is None or isinstance(value, timedelta):
return value
return timedelta(seconds=value)
| (self, func: ~T_before_serving) -> ~T_before_serving |
29,339 | quart.app | before_websocket | Add a before websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.before_websocket
async def func():
...
Arguments:
func: The before websocket function itself.
| from __future__ import annotations
import asyncio
import os
import signal
import sys
import warnings
from collections import defaultdict
from datetime import timedelta
from inspect import isasyncgen, isgenerator
from types import TracebackType
from typing import (
Any,
AnyStr,
AsyncGenerator,
Awaitable,
Callable,
cast,
Coroutine,
NoReturn,
Optional,
overload,
TypeVar,
Union,
)
from urllib.parse import quote
from weakref import WeakSet
from aiofiles import open as async_open
from aiofiles.base import AiofilesContextManager
from aiofiles.threadpool.binary import AsyncBufferedReader
from flask.sansio.app import App
from flask.sansio.scaffold import setupmethod
from hypercorn.asyncio import serve
from hypercorn.config import Config as HyperConfig
from hypercorn.typing import ASGIReceiveCallable, ASGISendCallable, Scope
from werkzeug.datastructures import Authorization, Headers, ImmutableDict
from werkzeug.exceptions import Aborter, BadRequestKeyError, HTTPException, InternalServerError
from werkzeug.routing import BuildError, MapAdapter, RoutingException
from werkzeug.wrappers import Response as WerkzeugResponse
from .asgi import ASGIHTTPConnection, ASGILifespan, ASGIWebsocketConnection
from .cli import AppGroup
from .config import Config
from .ctx import (
_AppCtxGlobals,
AppContext,
has_request_context,
has_websocket_context,
RequestContext,
WebsocketContext,
)
from .globals import (
_cv_app,
_cv_request,
_cv_websocket,
g,
request,
request_ctx,
session,
websocket,
websocket_ctx,
)
from .helpers import get_debug_flag, get_flashed_messages, send_from_directory
from .routing import QuartMap, QuartRule
from .sessions import SecureCookieSessionInterface
from .signals import (
appcontext_tearing_down,
got_background_exception,
got_request_exception,
got_serving_exception,
got_websocket_exception,
request_finished,
request_started,
request_tearing_down,
websocket_finished,
websocket_started,
websocket_tearing_down,
)
from .templating import _default_template_ctx_processor, Environment
from .testing import (
make_test_body_with_headers,
make_test_headers_path_and_query_string,
make_test_scope,
no_op_push,
QuartClient,
QuartCliRunner,
sentinel,
TestApp,
)
from .typing import (
AfterServingCallable,
AfterWebsocketCallable,
ASGIHTTPProtocol,
ASGILifespanProtocol,
ASGIWebsocketProtocol,
BeforeServingCallable,
BeforeWebsocketCallable,
Event,
FilePath,
HeadersValue,
ResponseReturnValue,
ResponseTypes,
ShellContextProcessorCallable,
StatusCode,
TeardownCallable,
TemplateFilterCallable,
TemplateGlobalCallable,
TemplateTestCallable,
TestAppProtocol,
TestClientProtocol,
WebsocketCallable,
WhileServingCallable,
)
from .utils import (
cancel_tasks,
file_path_to_path,
MustReloadError,
observe_changes,
restart,
run_sync,
)
from .wrappers import BaseRequestWebsocket, Request, Response, Websocket
try:
from typing import ParamSpec
except ImportError:
from typing_extensions import ParamSpec # type: ignore
AppOrBlueprintKey = Optional[str] # The App key is None, whereas blueprints are named
T_after_serving = TypeVar("T_after_serving", bound=AfterServingCallable)
T_after_websocket = TypeVar("T_after_websocket", bound=AfterWebsocketCallable)
T_before_serving = TypeVar("T_before_serving", bound=BeforeServingCallable)
T_before_websocket = TypeVar("T_before_websocket", bound=BeforeWebsocketCallable)
T_shell_context_processor = TypeVar(
"T_shell_context_processor", bound=ShellContextProcessorCallable
)
T_teardown = TypeVar("T_teardown", bound=TeardownCallable)
T_template_filter = TypeVar("T_template_filter", bound=TemplateFilterCallable)
T_template_global = TypeVar("T_template_global", bound=TemplateGlobalCallable)
T_template_test = TypeVar("T_template_test", bound=TemplateTestCallable)
T_websocket = TypeVar("T_websocket", bound=WebsocketCallable)
T_while_serving = TypeVar("T_while_serving", bound=WhileServingCallable)
T = TypeVar("T")
P = ParamSpec("P")
def _make_timedelta(value: timedelta | int | None) -> timedelta | None:
if value is None or isinstance(value, timedelta):
return value
return timedelta(seconds=value)
| (self, func: ~T_before_websocket) -> ~T_before_websocket |
29,342 | quart.app | create_jinja_environment | Create and return the jinja environment.
This will create the environment based on the
:attr:`jinja_options` and configuration settings. The
environment will include the Quart globals by default.
| def create_jinja_environment(self) -> Environment: # type: ignore
"""Create and return the jinja environment.
This will create the environment based on the
:attr:`jinja_options` and configuration settings. The
environment will include the Quart globals by default.
"""
options = dict(self.jinja_options)
if "autoescape" not in options:
options["autoescape"] = self.select_jinja_autoescape
if "auto_reload" not in options:
options["auto_reload"] = self.config["TEMPLATES_AUTO_RELOAD"]
jinja_env = self.jinja_environment(self, **options) # type: ignore
jinja_env.globals.update(
{
"config": self.config,
"g": g,
"get_flashed_messages": get_flashed_messages,
"request": request,
"session": session,
"url_for": self.url_for,
}
)
jinja_env.policies["json.dumps_function"] = self.json.dumps
return jinja_env
| (self) -> quart.templating.Environment |
29,343 | quart.app | create_url_adapter | Create and return a URL adapter.
This will create the adapter based on the request if present
otherwise the app configuration.
| def create_url_adapter(self, request: BaseRequestWebsocket | None) -> MapAdapter | None:
"""Create and return a URL adapter.
This will create the adapter based on the request if present
otherwise the app configuration.
"""
if request is not None:
subdomain = (
(self.url_map.default_subdomain or None) if not self.subdomain_matching else None
)
return self.url_map.bind_to_request( # type: ignore[attr-defined]
request, subdomain, self.config["SERVER_NAME"]
)
if self.config["SERVER_NAME"] is not None:
scheme = "https" if self.config["PREFER_SECURE_URLS"] else "http"
return self.url_map.bind(self.config["SERVER_NAME"], url_scheme=scheme)
return None
| (self, request: quart.wrappers.base.BaseRequestWebsocket | None) -> werkzeug.routing.map.MapAdapter | None |
29,345 | quart.app | dispatch_request | Dispatch the request to the view function.
Arguments:
request_context: The request context, optional as Flask
omits this argument.
| def raise_routing_exception(self, request: BaseRequestWebsocket) -> NoReturn:
raise request.routing_exception
| (self, request_context: Optional[quart.ctx.RequestContext] = None) -> Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], Union[werkzeug.datastructures.headers.Headers, Mapping[str, Union[str, List[str], Tuple[str, ...]]], Sequence[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], int], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], int, Union[werkzeug.datastructures.headers.Headers, Mapping[str, Union[str, List[str], Tuple[str, ...]]], Sequence[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]]] |
29,346 | quart.app | dispatch_websocket | Dispatch the websocket to the view function.
Arguments:
websocket_context: The websocket context, optional to match
the Flask convention.
| def raise_routing_exception(self, request: BaseRequestWebsocket) -> NoReturn:
raise request.routing_exception
| (self, websocket_context: Optional[quart.ctx.WebsocketContext] = None) -> Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], Union[werkzeug.datastructures.headers.Headers, Mapping[str, Union[str, List[str], Tuple[str, ...]]], Sequence[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], int], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], int, Union[werkzeug.datastructures.headers.Headers, Mapping[str, Union[str, List[str], Tuple[str, ...]]], Sequence[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], NoneType] |
29,347 | quart.app | do_teardown_appcontext | Teardown the app (context), calling the teardown functions. | def sync_to_async(self, func: Callable[P, T]) -> Callable[P, Awaitable[T]]:
"""Return a async function that will run the synchronous function *func*.
This can be used as so,::
result = await app.sync_to_async(func)(*args, **kwargs)
Override this method to change how the app converts sync code
to be asynchronously callable.
"""
return run_sync(func)
| (self, exc: BaseException | None) -> NoneType |
29,348 | quart.app | do_teardown_request | Teardown the request, calling the teardown functions.
Arguments:
exc: Any exception not handled that has caused the request
to teardown.
request_context: The request context, optional as Flask
omits this argument.
| def sync_to_async(self, func: Callable[P, T]) -> Callable[P, Awaitable[T]]:
"""Return a async function that will run the synchronous function *func*.
This can be used as so,::
result = await app.sync_to_async(func)(*args, **kwargs)
Override this method to change how the app converts sync code
to be asynchronously callable.
"""
return run_sync(func)
| (self, exc: BaseException | None, request_context: Optional[quart.ctx.RequestContext] = None) -> NoneType |
29,349 | quart.app | do_teardown_websocket | Teardown the websocket, calling the teardown functions.
Arguments:
exc: Any exception not handled that has caused the websocket
to teardown.
websocket_context: The websocket context, optional as Flask
omits this argument.
| def sync_to_async(self, func: Callable[P, T]) -> Callable[P, Awaitable[T]]:
"""Return a async function that will run the synchronous function *func*.
This can be used as so,::
result = await app.sync_to_async(func)(*args, **kwargs)
Override this method to change how the app converts sync code
to be asynchronously callable.
"""
return run_sync(func)
| (self, exc: BaseException | None, websocket_context: Optional[quart.ctx.WebsocketContext] = None) -> NoneType |
29,351 | quart.app | ensure_async | Ensure that the returned func is async and calls the func.
.. versionadded:: 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.
| def ensure_async(
self, func: Union[Callable[P, Awaitable[T]], Callable[P, T]]
) -> Callable[P, Awaitable[T]]:
"""Ensure that the returned func is async and calls the func.
.. versionadded:: 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.
"""
if asyncio.iscoroutinefunction(func):
return func
else:
return self.sync_to_async(cast(Callable[P, T], func))
| (self, func: Union[Callable[~P, Awaitable[~T]], Callable[~P, ~T]]) -> Callable[~P, Awaitable[~T]] |
29,353 | quart.app | finalize_request | Turns the view response return value into a response.
Arguments:
result: The result of the request to finalize into a response.
request_context: The request context, optional as Flask
omits this argument.
| def raise_routing_exception(self, request: BaseRequestWebsocket) -> NoReturn:
raise request.routing_exception
| (self, result: Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], Union[werkzeug.datastructures.headers.Headers, Mapping[str, Union[str, List[str], Tuple[str, ...]]], Sequence[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], int], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], int, Union[werkzeug.datastructures.headers.Headers, Mapping[str, Union[str, List[str], Tuple[str, ...]]], Sequence[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] |
29,354 | quart.app | finalize_websocket | Turns the view response return value into a response.
Arguments:
result: The result of the websocket to finalize into a response.
websocket_context: The websocket context, optional as Flask
omits this argument.
| def raise_routing_exception(self, request: BaseRequestWebsocket) -> NoReturn:
raise request.routing_exception
| (self, result: Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], Union[werkzeug.datastructures.headers.Headers, Mapping[str, Union[str, List[str], Tuple[str, ...]]], Sequence[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], int], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], int, Union[werkzeug.datastructures.headers.Headers, Mapping[str, Union[str, List[str], Tuple[str, ...]]], Sequence[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], werkzeug.exceptions.HTTPException], websocket_context: Optional[quart.ctx.WebsocketContext] = None, from_error_handler: bool = False) -> Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, NoneType] |
29,355 | quart.app | full_dispatch_request | Adds pre and post processing to the request dispatching.
Arguments:
request_context: The request context, optional as Flask
omits this argument.
| def add_background_task(self, func: Callable, *args: Any, **kwargs: Any) -> None:
async def _wrapper() -> None:
try:
async with self.app_context():
await self.ensure_async(func)(*args, **kwargs)
except Exception as error:
await self.handle_background_exception(error)
task = asyncio.get_event_loop().create_task(_wrapper())
self.background_tasks.add(task)
| (self, request_context: Optional[quart.ctx.RequestContext] = None) -> Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response] |
29,356 | quart.app | full_dispatch_websocket | Adds pre and post processing to the websocket dispatching.
Arguments:
websocket_context: The websocket context, optional to match
the Flask convention.
| def add_background_task(self, func: Callable, *args: Any, **kwargs: Any) -> None:
async def _wrapper() -> None:
try:
async with self.app_context():
await self.ensure_async(func)(*args, **kwargs)
except Exception as error:
await self.handle_background_exception(error)
task = asyncio.get_event_loop().create_task(_wrapper())
self.background_tasks.add(task)
| (self, websocket_context: Optional[quart.ctx.WebsocketContext] = None) -> Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, NoneType] |
29,358 | quart.app | get_send_file_max_age | Used by :func:`send_file` to determine the ``max_age`` cache
value for a given file path if it wasn't passed.
By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
the configuration of :data:`~flask.current_app`. This defaults
to ``None``, which tells the browser to use conditional requests
instead of a timed cache, which is usually preferable.
Note this is a duplicate of the same method in the Quart
class.
| def get_send_file_max_age(self, filename: str | None) -> int | None:
"""Used by :func:`send_file` to determine the ``max_age`` cache
value for a given file path if it wasn't passed.
By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
the configuration of :data:`~flask.current_app`. This defaults
to ``None``, which tells the browser to use conditional requests
instead of a timed cache, which is usually preferable.
Note this is a duplicate of the same method in the Quart
class.
"""
value = self.config["SEND_FILE_MAX_AGE_DEFAULT"]
if value is None:
return None
if isinstance(value, timedelta):
return int(value.total_seconds())
return value
return None
| (self, filename: str | None) -> int | None |
29,360 | quart.app | handle_exception | Handle an uncaught exception.
By default this switches the error response to a 500 internal
server error.
| @setupmethod
def teardown_websocket(
self,
func: T_teardown,
) -> T_teardown:
"""Add a teardown websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.teardown_websocket
async def func():
...
Arguments:
func: The teardown websocket function itself.
"""
self.teardown_websocket_funcs[None].append(func)
return func
| (self, error: Exception) -> Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response] |
29,361 | quart.app | handle_http_exception | 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.
| @setupmethod
def teardown_websocket(
self,
func: T_teardown,
) -> T_teardown:
"""Add a teardown websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.teardown_websocket
async def func():
...
Arguments:
func: The teardown websocket function itself.
"""
self.teardown_websocket_funcs[None].append(func)
return func
| (self, error: werkzeug.exceptions.HTTPException) -> Union[werkzeug.exceptions.HTTPException, quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], Union[werkzeug.datastructures.headers.Headers, Mapping[str, Union[str, List[str], Tuple[str, ...]]], Sequence[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], int], Tuple[Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, bytes, str, Mapping[str, Any], List[Any], Iterator[bytes], Iterator[str]], int, Union[werkzeug.datastructures.headers.Headers, Mapping[str, Union[str, List[str], Tuple[str, ...]]], Sequence[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]]] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.