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,364
quart.app
handle_user_exception
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.
@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[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, ...]]]]]]]
29,366
quart.app
handle_websocket_exception
Handle an uncaught exception. By default this logs the exception and then re-raises it.
@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, NoneType]
29,367
flask.sansio.app
inject_url_defaults
Injects the URL defaults for the given endpoint directly into the values dictionary passed. This is used internally and automatically called on URL building. .. versionadded:: 0.7
def inject_url_defaults(self, endpoint: str, values: dict[str, t.Any]) -> None: """Injects the URL defaults for the given endpoint directly into the values dictionary passed. This is used internally and automatically called on URL building. .. versionadded:: 0.7 """ names: t.Iterable[str | None] = (None,) # url_for may be called outside a request context, parse the # passed endpoint instead of using request.blueprints. if "." in endpoint: names = chain( names, reversed(_split_blueprint_path(endpoint.rpartition(".")[0])) ) for name in names: if name in self.url_default_functions: for func in self.url_default_functions[name]: func(endpoint, values)
(self, endpoint: str, values: dict[str, typing.Any]) -> NoneType
29,369
quart.app
log_exception
Log a exception to the :attr:`logger`. By default this is only invoked for unhandled exceptions.
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)
(self, exception_info: tuple[type, BaseException, traceback] | tuple[None, None, None]) -> NoneType
29,372
quart.app
make_default_options_response
This is the default route function for OPTIONS requests.
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) -> quart.wrappers.response.Response
29,373
quart.app
make_response
Make a Response from the result of the route handler. The result itself can either be: - A Response object (or subclass). - A tuple of a ResponseValue and a header dictionary. - A tuple of a ResponseValue, status code and a header dictionary. A ResponseValue is either a Response object (or subclass) or a str.
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, 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]) -> Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response]
29,374
quart.app
make_shell_context
Create a context for interactive shell usage. The :attr:`shell_context_processors` can be used to add additional context.
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
(self) -> dict
29,375
quart.app
open_instance_resource
Open a file for reading. Use as .. code-block:: python async with await app.open_instance_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 = 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, path: Union[bytes, str, os.PathLike], mode: str = 'rb') -> aiofiles.base.AiofilesContextManager[None, None, aiofiles.threadpool.binary.AsyncBufferedReader]
29,376
quart.app
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 = 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, path: Union[bytes, str, os.PathLike], mode: str = 'rb') -> aiofiles.base.AiofilesContextManager[None, None, aiofiles.threadpool.binary.AsyncBufferedReader]
29,379
quart.app
postprocess_websocket
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.
def raise_routing_exception(self, request: BaseRequestWebsocket) -> NoReturn: raise request.routing_exception
(self, response: Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response, NoneType], websocket_context: Optional[quart.ctx.WebsocketContext] = None) -> Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response]
29,380
quart.app
preprocess_request
Preprocess the request i.e. call before_request functions. 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, 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,381
quart.app
preprocess_websocket
Preprocess the websocket i.e. call before_websocket functions. Arguments: websocket_context: The websocket 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, 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,382
quart.app
process_response
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.
def raise_routing_exception(self, request: BaseRequestWebsocket) -> NoReturn: raise request.routing_exception
(self, response: Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response], request_context: Optional[quart.ctx.RequestContext] = None) -> Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response]
29,384
quart.app
raise_routing_exception
null
def raise_routing_exception(self, request: BaseRequestWebsocket) -> NoReturn: raise request.routing_exception
(self, request: quart.wrappers.base.BaseRequestWebsocket) -> NoReturn
29,385
flask.sansio.app
redirect
Create a redirect response object. This is called by :func:`flask.redirect`, and can be called directly as well. :param location: The URL to redirect to. :param code: The status code for the redirect. .. versionadded:: 2.2 Moved from ``flask.redirect``, which calls this method.
def redirect(self, location: str, code: int = 302) -> BaseResponse: """Create a redirect response object. This is called by :func:`flask.redirect`, and can be called directly as well. :param location: The URL to redirect to. :param code: The status code for the redirect. .. versionadded:: 2.2 Moved from ``flask.redirect``, which calls this method. """ return _wz_redirect( location, code=code, Response=self.response_class, # type: ignore[arg-type] )
(self, location: 'str', code: 'int' = 302) -> 'BaseResponse'
29,386
flask.sansio.app
register_blueprint
Register a :class:`~flask.Blueprint` on the application. Keyword arguments passed to this method will override the defaults set on the blueprint. Calls the blueprint's :meth:`~flask.Blueprint.register` method after recording the blueprint in the application's :attr:`blueprints`. :param blueprint: The blueprint to register. :param url_prefix: Blueprint routes will be prefixed with this. :param subdomain: Blueprint routes will match on this subdomain. :param url_defaults: Blueprint routes will use these default values for view arguments. :param options: Additional keyword arguments are passed to :class:`~flask.blueprints.BlueprintSetupState`. They can be accessed in :meth:`~flask.Blueprint.record` callbacks. .. versionchanged:: 2.0.1 The ``name`` option can be used to change the (pre-dotted) name the blueprint is registered with. This allows the same blueprint to be registered multiple times with unique names for ``url_for``. .. versionadded:: 0.7
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, blueprint: 'Blueprint', **options: 't.Any') -> 'None'
29,388
quart.app
request_context
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.
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)
(self, request: quart.wrappers.request.Request) -> quart.ctx.RequestContext
29,390
quart.app
run
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.
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()
(self, host: Optional[str] = None, port: Optional[int] = None, debug: Optional[bool] = None, use_reloader: bool = True, loop: Optional[asyncio.events.AbstractEventLoop] = None, ca_certs: Optional[str] = None, certfile: Optional[str] = None, keyfile: Optional[str] = None, **kwargs: Any) -> NoneType
29,391
quart.app
run_task
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.
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)
(self, host: str = '127.0.0.1', port: int = 5000, debug: Optional[bool] = None, ca_certs: Optional[str] = None, certfile: Optional[str] = None, keyfile: Optional[str] = None, shutdown_trigger: Optional[Callable[..., Awaitable[NoneType]]] = None) -> Coroutine[NoneType, NoneType, NoneType]
29,393
quart.app
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 = 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) -> quart.wrappers.response.Response
29,394
flask.sansio.app
shell_context_processor
Registers a shell context processor function. .. versionadded:: 0.11
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: ~T_shell_context_processor) -> ~T_shell_context_processor
29,398
quart.app
sync_to_async
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.
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, func: Callable[~P, ~T]) -> Callable[~P, Awaitable[~T]]
29,399
flask.sansio.app
teardown_appcontext
Registers a function to be called when the application context is popped. The application context is typically popped after the request context for each request, at the end of CLI commands, or after a manually pushed context ends. .. code-block:: python with app.app_context(): ... When the ``with`` block exits (or ``ctx.pop()`` is called), the teardown functions are called just before the app context is made inactive. Since a request context typically also manages an application context it would also be called when you pop a request context. When a teardown function was called because of an unhandled exception it will be passed an error object. If an :meth:`errorhandler` is registered, it will handle the exception and the teardown will not receive it. Teardown functions must avoid raising exceptions. If they execute code that might fail they must surround that code with a ``try``/``except`` block and log any errors. The return values of teardown functions are ignored. .. versionadded:: 0.9
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: ~T_teardown) -> ~T_teardown
29,401
quart.app
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.
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_teardown) -> ~T_teardown
29,402
flask.sansio.app
template_filter
A decorator that is used to register custom template filter. You can specify a name for the filter, otherwise the function name will be used. Example:: @app.template_filter() def reverse(s): return s[::-1] :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, name: str | None = None) -> Callable[[~T_template_filter], ~T_template_filter]
29,403
flask.sansio.app
template_global
A decorator that is used to register a custom template global function. You can specify a name for the global function, otherwise the function name will be used. Example:: @app.template_global() def double(n): return 2 * n .. 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, name: str | None = None) -> Callable[[~T_template_global], ~T_template_global]
29,404
flask.sansio.app
template_test
A decorator that is used to register custom template test. You can specify a name for the test, otherwise the function name will be used. Example:: @app.template_test() def is_prime(n): if n == 2: return True for i in range(2, int(math.ceil(math.sqrt(n))) + 1): if n % i == 0: return False return True .. 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, name: str | None = None) -> Callable[[~T_template_test], ~T_template_test]
29,405
quart.app
test_app
null
def test_app(self) -> TestAppProtocol: return self.test_app_class(self)
(self) -> quart.typing.TestAppProtocol
29,406
quart.app
test_cli_runner
Creates and returns a CLI test runner.
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
(self, **kwargs: Any) -> quart.testing.QuartCliRunner
29,407
quart.app
test_client
Creates and returns a test client.
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)
(self, use_cookies: bool = True, **kwargs: Any) -> quart.typing.TestClientProtocol
29,408
quart.app
test_request_context
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.
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)
(self, path: str, *, method: str = 'GET', headers: Union[dict, werkzeug.datastructures.headers.Headers, NoneType] = None, query_string: Optional[dict] = None, scheme: str = 'http', send_push_promise: Callable[[str, werkzeug.datastructures.headers.Headers], Awaitable[NoneType]] = <function no_op_push at 0x7fa5940672e0>, data: Optional[~AnyStr] = None, form: Optional[dict] = None, json: Any = <object object at 0x7fa59615ab20>, root_path: str = '', http_version: str = '1.1', scope_base: Optional[dict] = None, auth: Union[werkzeug.datastructures.auth.Authorization, tuple[str, str], NoneType] = None, subdomain: Optional[str] = None) -> quart.ctx.RequestContext
29,410
quart.app
update_template_context
Update the provided template context. This adds additional context from the various template context processors. Arguments: context: The context to update (mutate).
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, context: dict) -> NoneType
29,412
quart.app
url_for
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.
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
(self, endpoint: str, *, _anchor: Optional[str] = None, _external: Optional[bool] = None, _method: Optional[str] = None, _scheme: Optional[str] = None, **values: Any) -> str
29,414
quart.app
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: 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
(self, rule: str, **options: Any) -> Callable[[~T_websocket], ~T_websocket]
29,415
quart.app
websocket_context
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.
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)
(self, websocket: quart.wrappers.websocket.Websocket) -> quart.ctx.WebsocketContext
29,416
quart.app
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.
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_while_serving) -> ~T_while_serving
29,417
quart.wrappers.request
Request
This class represents a request. It can be subclassed and the subclassed used in preference by replacing the :attr:`~quart.Quart.request_class` with your subclass. Attributes: body_class: The class to store the body data within. form_data_parser_class: Can be overridden to implement a different form data parsing.
class Request(BaseRequestWebsocket): """This class represents a request. It can be subclassed and the subclassed used in preference by replacing the :attr:`~quart.Quart.request_class` with your subclass. Attributes: body_class: The class to store the body data within. form_data_parser_class: Can be overridden to implement a different form data parsing. """ body_class = Body form_data_parser_class = FormDataParser lock_class = asyncio.Lock def __init__( self, method: str, scheme: str, path: str, query_string: bytes, headers: Headers, root_path: str, http_version: str, scope: HTTPScope, *, max_content_length: int | None = None, body_timeout: int | None = None, send_push_promise: Callable[[str, Headers], Awaitable[None]], ) -> None: """Create a request object. Arguments: method: The HTTP verb. scheme: The scheme used for the request. path: The full unquoted path of the request. query_string: The raw bytes for the query string part. headers: The request headers. root_path: The root path that should be prepended to all routes. http_version: The HTTP version of the request. body: An awaitable future for the body data i.e. ``data = await body`` max_content_length: The maximum length in bytes of the body (None implies no limit in Quart). body_timeout: The maximum time (seconds) to wait for the body before timing out. send_push_promise: An awaitable to send a push promise based off of this request (HTTP/2 feature). scope: Underlying ASGI scope dictionary. """ super().__init__( method, scheme, path, query_string, headers, root_path, http_version, scope ) self.body_timeout = body_timeout self.body = self.body_class(self.content_length, max_content_length) self._cached_json: dict[bool, Any] = {False: Ellipsis, True: Ellipsis} self._form: MultiDict | None = None self._files: MultiDict | None = None self._parsing_lock = self.lock_class() self._send_push_promise = send_push_promise @property async def stream(self) -> NoReturn: raise NotImplementedError("Use body instead") @property async def data(self) -> bytes: return await self.get_data(as_text=False, parse_form_data=True) @overload async def get_data( self, cache: bool, as_text: Literal[False], parse_form_data: bool ) -> bytes: ... @overload async def get_data(self, cache: bool, as_text: Literal[True], parse_form_data: bool) -> str: ... @overload async def get_data( self, cache: bool = True, as_text: bool = False, parse_form_data: bool = False ) -> AnyStr: ... async def get_data( self, cache: bool = True, as_text: bool = False, parse_form_data: bool = False ) -> AnyStr: """Get the request body data. Arguments: cache: If False the body data will be cleared, resulting in any subsequent calls returning an empty AnyStr and reducing memory usage. as_text: If True the data is returned as a decoded string, otherwise raw bytes are returned. parse_form_data: Parse the data as form data first, return any remaining data. """ if parse_form_data: await self._load_form_data() try: raw_data = await asyncio.wait_for(self.body, timeout=self.body_timeout) except asyncio.TimeoutError: raise RequestTimeout() else: if not cache: self.body.clear() if as_text: return raw_data.decode() else: return raw_data @property async def values(self) -> CombinedMultiDict: sources = [self.args] if self.method != "GET": # Whilst GET requests are allowed to have a body, most # implementations do not allow this hence this # inconsistency may result in confusing values. form = await self.form sources.append(form) multidict_sources: list[MultiDict] = [] for source in sources: if not isinstance(source, MultiDict): multidict_sources.append(MultiDict(source)) else: multidict_sources.append(source) return CombinedMultiDict(multidict_sources) @property async def form(self) -> MultiDict: """The parsed form encoded data. Note file data is present in the :attr:`files`. """ await self._load_form_data() return self._form @property async def files(self) -> MultiDict: """The parsed files. This will return an empty multidict unless the request mimetype was ``enctype="multipart/form-data"`` and the method POST, PUT, or PATCH. """ await self._load_form_data() return self._files def make_form_data_parser(self) -> FormDataParser: return self.form_data_parser_class( max_content_length=self.max_content_length, cls=self.parameter_storage_class, ) async def _load_form_data(self) -> None: async with self._parsing_lock: if self._form is None: parser = self.make_form_data_parser() try: self._form, self._files = await asyncio.wait_for( parser.parse( self.body, self.mimetype, self.content_length, self.mimetype_params, ), timeout=self.body_timeout, ) except asyncio.TimeoutError: raise RequestTimeout() @property async def json(self) -> Any: return await self.get_json() async def get_json(self, force: bool = False, silent: bool = False, cache: bool = True) -> Any: """Parses the body data as JSON and returns it. Arguments: force: Force JSON parsing even if the mimetype is not JSON. silent: Do not trigger error handling if parsing fails, without this the :meth:`on_json_loading_failed` will be called on error. cache: Cache the parsed JSON on this request object. """ if cache and self._cached_json[silent] is not Ellipsis: return self._cached_json[silent] if not (force or self.is_json): return None data = await self.get_data(cache=cache, as_text=True) try: result = self.json_module.loads(data) except ValueError as error: if silent: result = None else: result = self.on_json_loading_failed(error) if cache: self._cached_json[silent] = result return result def on_json_loading_failed(self, error: Exception) -> Any: """Handle a JSON parsing error. Arguments: error: The exception raised during parsing. Returns: Any value returned (if overridden) will be used as the default for any get_json calls. """ if current_app and current_app.debug: raise BadRequest(f"Failed to decode JSON: {error}") raise BadRequest() async def send_push_promise(self, path: str) -> None: headers = Headers() for name in SERVER_PUSH_HEADERS_TO_COPY: for value in self.headers.getlist(name): headers.add(name, value) await self._send_push_promise(path, headers) async def close(self) -> None: for _key, value in iter_multi_items(self._files or ()): value.close()
(method: 'str', scheme: 'str', path: 'str', query_string: 'bytes', headers: 'Headers', root_path: 'str', http_version: 'str', scope: 'HTTPScope', *, max_content_length: 'int | None' = None, body_timeout: 'int | None' = None, send_push_promise: 'Callable[[str, Headers], Awaitable[None]]') -> 'None'
29,418
quart.wrappers.request
__init__
Create a request object. Arguments: method: The HTTP verb. scheme: The scheme used for the request. path: The full unquoted path of the request. query_string: The raw bytes for the query string part. headers: The request headers. root_path: The root path that should be prepended to all routes. http_version: The HTTP version of the request. body: An awaitable future for the body data i.e. ``data = await body`` max_content_length: The maximum length in bytes of the body (None implies no limit in Quart). body_timeout: The maximum time (seconds) to wait for the body before timing out. send_push_promise: An awaitable to send a push promise based off of this request (HTTP/2 feature). scope: Underlying ASGI scope dictionary.
def __init__( self, method: str, scheme: str, path: str, query_string: bytes, headers: Headers, root_path: str, http_version: str, scope: HTTPScope, *, max_content_length: int | None = None, body_timeout: int | None = None, send_push_promise: Callable[[str, Headers], Awaitable[None]], ) -> None: """Create a request object. Arguments: method: The HTTP verb. scheme: The scheme used for the request. path: The full unquoted path of the request. query_string: The raw bytes for the query string part. headers: The request headers. root_path: The root path that should be prepended to all routes. http_version: The HTTP version of the request. body: An awaitable future for the body data i.e. ``data = await body`` max_content_length: The maximum length in bytes of the body (None implies no limit in Quart). body_timeout: The maximum time (seconds) to wait for the body before timing out. send_push_promise: An awaitable to send a push promise based off of this request (HTTP/2 feature). scope: Underlying ASGI scope dictionary. """ super().__init__( method, scheme, path, query_string, headers, root_path, http_version, scope ) self.body_timeout = body_timeout self.body = self.body_class(self.content_length, max_content_length) self._cached_json: dict[bool, Any] = {False: Ellipsis, True: Ellipsis} self._form: MultiDict | None = None self._files: MultiDict | None = None self._parsing_lock = self.lock_class() self._send_push_promise = send_push_promise
(self, method: str, scheme: str, path: str, query_string: bytes, headers: werkzeug.datastructures.headers.Headers, root_path: str, http_version: str, scope: hypercorn.typing.HTTPScope, *, max_content_length: Optional[int] = None, body_timeout: Optional[int] = None, send_push_promise: Callable[[str, werkzeug.datastructures.headers.Headers], Awaitable[NoneType]]) -> NoneType
29,419
werkzeug.sansio.request
__repr__
null
def __repr__(self) -> str: try: url = self.url except Exception as e: url = f"(invalid URL: {e})" return f"<{type(self).__name__} {url!r} [{self.method}]>"
(self) -> str
29,420
quart.wrappers.request
_load_form_data
null
def make_form_data_parser(self) -> FormDataParser: return self.form_data_parser_class( max_content_length=self.max_content_length, cls=self.parameter_storage_class, )
(self) -> NoneType
29,421
werkzeug.sansio.request
_parse_content_type
null
def _parse_content_type(self) -> None: if not hasattr(self, "_parsed_content_type"): self._parsed_content_type = parse_options_header( self.headers.get("Content-Type", "") )
(self) -> NoneType
29,422
quart.wrappers.request
close
null
def on_json_loading_failed(self, error: Exception) -> Any: """Handle a JSON parsing error. Arguments: error: The exception raised during parsing. Returns: Any value returned (if overridden) will be used as the default for any get_json calls. """ if current_app and current_app.debug: raise BadRequest(f"Failed to decode JSON: {error}") raise BadRequest()
(self) -> NoneType
29,423
quart.wrappers.request
get_data
Get the request body data. Arguments: cache: If False the body data will be cleared, resulting in any subsequent calls returning an empty AnyStr and reducing memory usage. as_text: If True the data is returned as a decoded string, otherwise raw bytes are returned. parse_form_data: Parse the data as form data first, return any remaining data.
@overload async def get_data( self, cache: bool = True, as_text: bool = False, parse_form_data: bool = False ) -> AnyStr: ...
(self, cache: bool = True, as_text: bool = False, parse_form_data: bool = False) -> ~AnyStr
29,424
quart.wrappers.request
get_json
Parses the body data as JSON and returns it. Arguments: force: Force JSON parsing even if the mimetype is not JSON. silent: Do not trigger error handling if parsing fails, without this the :meth:`on_json_loading_failed` will be called on error. cache: Cache the parsed JSON on this request object.
@property async def json(self) -> Any: return await self.get_json()
(self, force: bool = False, silent: bool = False, cache: bool = True) -> Any
29,426
quart.wrappers.request
on_json_loading_failed
Handle a JSON parsing error. Arguments: error: The exception raised during parsing. Returns: Any value returned (if overridden) will be used as the default for any get_json calls.
def on_json_loading_failed(self, error: Exception) -> Any: """Handle a JSON parsing error. Arguments: error: The exception raised during parsing. Returns: Any value returned (if overridden) will be used as the default for any get_json calls. """ if current_app and current_app.debug: raise BadRequest(f"Failed to decode JSON: {error}") raise BadRequest()
(self, error: Exception) -> Any
29,428
quart.wrappers.response
Response
This class represents a response. It can be subclassed and the subclassed used in preference by replacing the :attr:`~quart.Quart.response_class` with your subclass. Attributes: automatically_set_content_length: If False the content length header must be provided. default_status: The status code to use if not provided. default_mimetype: The mimetype to use if not provided. implicit_sequence_conversion: Implicitly convert the response to a iterable in the get_data method, to allow multiple iterations.
class Response(SansIOResponse): """This class represents a response. It can be subclassed and the subclassed used in preference by replacing the :attr:`~quart.Quart.response_class` with your subclass. Attributes: automatically_set_content_length: If False the content length header must be provided. default_status: The status code to use if not provided. default_mimetype: The mimetype to use if not provided. implicit_sequence_conversion: Implicitly convert the response to a iterable in the get_data method, to allow multiple iterations. """ automatically_set_content_length = True default_mimetype = "text/html" data_body_class = DataBody file_body_class = FileBody implicit_sequence_conversion = True io_body_class = IOBody iterable_body_class = IterableBody json_module = json def __init__( self, response: ResponseBody | AnyStr | Iterable | None = None, status: int | None = None, headers: dict | Headers | None = None, mimetype: str | None = None, content_type: str | None = None, ) -> None: """Create a response object. The response itself can be a chunk of data or a iterable/generator of data chunks. The Content-Type can either be specified as a mimetype or content_type header or omitted to use the :attr:`default_mimetype`. Arguments: response: The response data or iterable over the data. status: Status code of the response. headers: Headers to attach to the response. mimetype: Mimetype of the response. content_type: Content-Type header value. Attributes: response: An iterable of the response bytes-data. """ super().__init__(status, headers, mimetype, content_type) self.timeout: Any = Ellipsis self.response: ResponseBody if response is None: self.response = self.iterable_body_class([]) elif isinstance(response, ResponseBody): self.response = response elif isinstance(response, (str, bytes)): self.set_data(response) # type: ignore else: self.response = self.iterable_body_class(response) @property def max_cookie_size(self) -> int: # type: ignore if current_app: return current_app.config["MAX_COOKIE_SIZE"] return super().max_cookie_size @overload async def get_data(self, as_text: Literal[True]) -> str: ... @overload async def get_data(self, as_text: Literal[False]) -> bytes: ... @overload async def get_data(self, as_text: bool = True) -> AnyStr: ... async def get_data(self, as_text: bool = False) -> AnyStr: """Return the body data.""" if self.implicit_sequence_conversion: await self.make_sequence() result = "" if as_text else b"" async with self.response as body: async for data in body: if as_text: result += data.decode() else: result += data return result # type: ignore def set_data(self, data: AnyStr) -> None: """Set the response data. This will encode using the :attr:`charset`. """ if isinstance(data, str): bytes_data = data.encode() else: bytes_data = data self.response = self.data_body_class(bytes_data) if self.automatically_set_content_length: self.content_length = len(bytes_data) @property async def data(self) -> bytes: return await self.get_data() @data.setter def data(self, value: bytes) -> None: self.set_data(value) @property async def json(self) -> Any: return await self.get_json() async def get_json(self, force: bool = False, silent: bool = False) -> Any: """Parses the body data as JSON and returns it. Arguments: force: Force JSON parsing even if the mimetype is not JSON. silent: Do not trigger error handling if parsing fails, without this the :meth:`on_json_loading_failed` will be called on error. """ if not (force or self.is_json): return None data = await self.get_data(as_text=True) try: return self.json_module.loads(data) except ValueError: if silent: raise return None def _is_range_request_processable(self, request: Request) -> bool: return ( "If-Range" not in request.headers or not is_resource_modified( http_range=request.headers.get("Range"), http_if_range=request.headers.get("If-Range"), http_if_modified_since=request.headers.get("If-Modified-Since"), http_if_none_match=request.headers.get("If-None-Match"), http_if_match=request.headers.get("If-Match"), etag=self.headers.get("etag"), data=None, last_modified=self.headers.get("last-modified"), ignore_if_range=False, ) ) and "Range" in request.headers async def _process_range_request( self, request: Request, complete_length: int | None = None, accept_ranges: str | None = None, ) -> bool: if ( accept_ranges is None or complete_length is None or complete_length == 0 or not self._is_range_request_processable(request) ): return False request_range = request.range if request_range is None: raise RequestedRangeNotSatisfiable(complete_length) if request_range.units != "bytes" or len(request_range.ranges) > 1: raise RequestedRangeNotSatisfiable() begin, end = request_range.ranges[0] try: complete_length = await self.response.make_conditional(begin, end) # type: ignore except AttributeError: await self.make_sequence() complete_length = await self.response.make_conditional(begin, end) # type: ignore self.content_length = self.response.end - self.response.begin # type: ignore self.headers["Accept-Ranges"] = accept_ranges self.content_range = ContentRange( request_range.units, self.response.begin, # type: ignore self.response.end - 1, # type: ignore complete_length, ) self.status_code = 206 return True async def make_conditional( self, request: Request, accept_ranges: bool | str = False, complete_length: int | None = None, ) -> Response: if request.method in {"GET", "HEAD"}: accept_ranges = _clean_accept_ranges(accept_ranges) is206 = await self._process_range_request(request, complete_length, accept_ranges) if not is206 and not is_resource_modified( http_range=request.headers.get("Range"), http_if_range=request.headers.get("If-Range"), http_if_modified_since=request.headers.get("If-Modified-Since"), http_if_none_match=request.headers.get("If-None-Match"), http_if_match=request.headers.get("If-Match"), etag=self.headers.get("etag"), data=None, last_modified=self.headers.get("last-modified"), ignore_if_range=True, ): if parse_etags(request.headers.get("If-Match")): self.status_code = 412 else: self.status_code = 304 self.set_data(b"") del self.content_length return self async def make_sequence(self) -> None: data = b"".join([value async for value in self.iter_encode()]) self.response = self.data_body_class(data) async def iter_encode(self) -> AsyncGenerator[bytes, None]: async with self.response as response_body: async for item in response_body: if isinstance(item, str): yield item.encode() else: yield item async def freeze(self) -> None: """Freeze this object ready for pickling.""" self.set_data(await self.get_data()) async def add_etag(self, overwrite: bool = False, weak: bool = False) -> None: if overwrite or "etag" not in self.headers: self.set_etag(md5(await self.get_data(as_text=False)).hexdigest(), weak) def _set_or_pop_header(self, key: str, value: str) -> None: if value == "": self.headers.pop(key, None) else: self.headers[key] = value
(response: 'ResponseBody | AnyStr | Iterable | None' = None, status: 'int | None' = None, headers: werkzeug.datastructures.headers.Headers = None, mimetype: 'str | None' = None, content_type: 'str | None' = None) -> 'None'
29,429
quart.wrappers.response
__init__
Create a response object. The response itself can be a chunk of data or a iterable/generator of data chunks. The Content-Type can either be specified as a mimetype or content_type header or omitted to use the :attr:`default_mimetype`. Arguments: response: The response data or iterable over the data. status: Status code of the response. headers: Headers to attach to the response. mimetype: Mimetype of the response. content_type: Content-Type header value. Attributes: response: An iterable of the response bytes-data.
def __init__( self, response: ResponseBody | AnyStr | Iterable | None = None, status: int | None = None, headers: dict | Headers | None = None, mimetype: str | None = None, content_type: str | None = None, ) -> None: """Create a response object. The response itself can be a chunk of data or a iterable/generator of data chunks. The Content-Type can either be specified as a mimetype or content_type header or omitted to use the :attr:`default_mimetype`. Arguments: response: The response data or iterable over the data. status: Status code of the response. headers: Headers to attach to the response. mimetype: Mimetype of the response. content_type: Content-Type header value. Attributes: response: An iterable of the response bytes-data. """ super().__init__(status, headers, mimetype, content_type) self.timeout: Any = Ellipsis self.response: ResponseBody if response is None: self.response = self.iterable_body_class([]) elif isinstance(response, ResponseBody): self.response = response elif isinstance(response, (str, bytes)): self.set_data(response) # type: ignore else: self.response = self.iterable_body_class(response)
(self, response: Union[quart.wrappers.response.ResponseBody, ~AnyStr, Iterable, NoneType] = None, status: Optional[int] = None, headers: Union[dict, werkzeug.datastructures.headers.Headers, NoneType] = None, mimetype: Optional[str] = None, content_type: Optional[str] = None) -> NoneType
29,430
werkzeug.sansio.response
__repr__
null
def __repr__(self) -> str: return f"<{type(self).__name__} [{self.status}]>"
(self) -> str
29,432
quart.wrappers.response
_is_range_request_processable
null
def _is_range_request_processable(self, request: Request) -> bool: return ( "If-Range" not in request.headers or not is_resource_modified( http_range=request.headers.get("Range"), http_if_range=request.headers.get("If-Range"), http_if_modified_since=request.headers.get("If-Modified-Since"), http_if_none_match=request.headers.get("If-None-Match"), http_if_match=request.headers.get("If-Match"), etag=self.headers.get("etag"), data=None, last_modified=self.headers.get("last-modified"), ignore_if_range=False, ) ) and "Range" in request.headers
(self, request: 'Request') -> 'bool'
29,434
quart.wrappers.response
_set_or_pop_header
null
def _set_or_pop_header(self, key: str, value: str) -> None: if value == "": self.headers.pop(key, None) else: self.headers[key] = value
(self, key: str, value: str) -> NoneType
29,437
quart.wrappers.response
freeze
Freeze this object ready for pickling.
def _is_range_request_processable(self, request: Request) -> bool: return ( "If-Range" not in request.headers or not is_resource_modified( http_range=request.headers.get("Range"), http_if_range=request.headers.get("If-Range"), http_if_modified_since=request.headers.get("If-Modified-Since"), http_if_none_match=request.headers.get("If-None-Match"), http_if_match=request.headers.get("If-Match"), etag=self.headers.get("etag"), data=None, last_modified=self.headers.get("last-modified"), ignore_if_range=False, ) ) and "Range" in request.headers
(self) -> NoneType
29,438
quart.wrappers.response
get_data
Return the body data.
@overload async def get_data(self, as_text: bool = True) -> AnyStr: ...
(self, as_text: bool = False) -> ~AnyStr
29,440
quart.wrappers.response
get_json
Parses the body data as JSON and returns it. Arguments: force: Force JSON parsing even if the mimetype is not JSON. silent: Do not trigger error handling if parsing fails, without this the :meth:`on_json_loading_failed` will be called on error.
@property async def json(self) -> Any: return await self.get_json()
(self, force: bool = False, silent: bool = False) -> Any
29,445
quart.wrappers.response
set_data
Set the response data. This will encode using the :attr:`charset`.
def set_data(self, data: AnyStr) -> None: """Set the response data. This will encode using the :attr:`charset`. """ if isinstance(data, str): bytes_data = data.encode() else: bytes_data = data self.response = self.data_body_class(bytes_data) if self.automatically_set_content_length: self.content_length = len(bytes_data)
(self, data: ~AnyStr) -> NoneType
29,447
quart.wrappers.websocket
Websocket
null
class Websocket(BaseRequestWebsocket): def __init__( self, path: str, query_string: bytes, scheme: str, headers: Headers, root_path: str, http_version: str, subprotocols: list[str], receive: Callable, send: Callable, accept: Callable, close: Callable, scope: WebsocketScope, ) -> None: """Create a request object. Arguments: path: The full unquoted path of the request. query_string: The raw bytes for the query string part. scheme: The scheme used for the request. headers: The request headers. root_path: The root path that should be prepended to all routes. http_version: The HTTP version of the request. subprotocols: The subprotocols requested. receive: Returns an awaitable of the current data accept: Idempotent callable to accept the websocket connection. scope: Underlying ASGI scope dictionary. """ super().__init__("GET", scheme, path, query_string, headers, root_path, http_version, scope) self._accept = accept self._close = close self._receive = receive self._send = send self._subprotocols = subprotocols @property def requested_subprotocols(self) -> list[str]: return self._subprotocols async def receive(self) -> AnyStr: await self.accept() return await self._receive() async def send(self, data: AnyStr) -> None: # Must allow for the event loop to act if the user has say # setup a tight loop sending data over a websocket (as in the # example). So yield via the sleep. await asyncio.sleep(0) await self.accept() await self._send(data) async def receive_json(self) -> Any: data = await self.receive() return self.json_module.loads(data) async def send_json(self, *args: Any, **kwargs: Any) -> None: if args and kwargs: raise TypeError("jsonify() behavior undefined when passed both args and kwargs") elif len(args) == 1: data = args[0] else: data = args or kwargs raw = self.json_module.dumps(data) await self.send(raw) async def accept( self, headers: dict | Headers | None = None, subprotocol: str | None = None ) -> None: """Manually chose to accept the websocket connection. Arguments: headers: Additional headers to send with the acceptance response. subprotocol: The chosen subprotocol, optional. """ if headers is None: headers_ = Headers() else: headers_ = Headers(headers) await self._accept(headers_, subprotocol) async def close(self, code: int, reason: str = "") -> None: await self._close(code, reason)
(path: 'str', query_string: 'bytes', scheme: 'str', headers: 'Headers', root_path: 'str', http_version: 'str', subprotocols: 'list[str]', receive: 'Callable', send: 'Callable', accept: 'Callable', close: 'Callable', scope: 'WebsocketScope') -> 'None'
29,448
quart.wrappers.websocket
__init__
Create a request object. Arguments: path: The full unquoted path of the request. query_string: The raw bytes for the query string part. scheme: The scheme used for the request. headers: The request headers. root_path: The root path that should be prepended to all routes. http_version: The HTTP version of the request. subprotocols: The subprotocols requested. receive: Returns an awaitable of the current data accept: Idempotent callable to accept the websocket connection. scope: Underlying ASGI scope dictionary.
def __init__( self, path: str, query_string: bytes, scheme: str, headers: Headers, root_path: str, http_version: str, subprotocols: list[str], receive: Callable, send: Callable, accept: Callable, close: Callable, scope: WebsocketScope, ) -> None: """Create a request object. Arguments: path: The full unquoted path of the request. query_string: The raw bytes for the query string part. scheme: The scheme used for the request. headers: The request headers. root_path: The root path that should be prepended to all routes. http_version: The HTTP version of the request. subprotocols: The subprotocols requested. receive: Returns an awaitable of the current data accept: Idempotent callable to accept the websocket connection. scope: Underlying ASGI scope dictionary. """ super().__init__("GET", scheme, path, query_string, headers, root_path, http_version, scope) self._accept = accept self._close = close self._receive = receive self._send = send self._subprotocols = subprotocols
(self, path: str, query_string: bytes, scheme: str, headers: werkzeug.datastructures.headers.Headers, root_path: str, http_version: str, subprotocols: list[str], receive: Callable, send: Callable, accept: Callable, close: Callable, scope: hypercorn.typing.WebsocketScope) -> NoneType
29,451
quart.wrappers.websocket
accept
Manually chose to accept the websocket connection. Arguments: headers: Additional headers to send with the acceptance response. subprotocol: The chosen subprotocol, optional.
@property def requested_subprotocols(self) -> list[str]: return self._subprotocols
(self, headers: Union[dict, werkzeug.datastructures.headers.Headers, NoneType] = None, subprotocol: Optional[str] = None) -> NoneType
29,452
quart.wrappers.websocket
close
null
@property def requested_subprotocols(self) -> list[str]: return self._subprotocols
(self, code: int, reason: str = '') -> NoneType
29,457
quart.helpers
abort
Raise an HTTPException for the given status code.
def abort(code: int | Response, *args: Any, **kwargs: Any) -> NoReturn: """Raise an HTTPException for the given status code.""" if current_app: current_app.aborter(code, *args, **kwargs) werkzeug_abort(code, *args, **kwargs)
(code: int | quart.wrappers.response.Response, *args: Any, **kwargs: Any) -> NoReturn
29,458
quart.ctx
after_this_request
Schedule the func to be called after the current request. This is useful in situations whereby you want an after request function for a specific route or circumstance only, for example, .. code-block:: python def index(): @after_this_request def set_cookie(response): response.set_cookie('special', 'value') return response ...
def after_this_request(func: AfterRequestCallable) -> AfterRequestCallable: """Schedule the func to be called after the current request. This is useful in situations whereby you want an after request function for a specific route or circumstance only, for example, .. code-block:: python def index(): @after_this_request def set_cookie(response): response.set_cookie('special', 'value') return response ... """ ctx = _cv_request.get(None) if ctx is None: raise RuntimeError("Not within a request context") ctx._after_request_functions.append(func) return func
(func: 'AfterRequestCallable') -> 'AfterRequestCallable'
29,464
quart.ctx
copy_current_app_context
Share the current app context with the function decorated. The app context is local per task and hence will not be available in any other task. This decorator can be used to make the context available, .. code-block:: python @copy_current_app_context async def within_context() -> None: name = current_app.name ...
def copy_current_app_context(func: Callable) -> Callable: """Share the current app context with the function decorated. The app context is local per task and hence will not be available in any other task. This decorator can be used to make the context available, .. code-block:: python @copy_current_app_context async def within_context() -> None: name = current_app.name ... """ if not has_app_context(): raise RuntimeError("Attempt to copy app context outside of a app context") app_context = _cv_app.get().copy() @wraps(func) async def wrapper(*args: Any, **kwargs: Any) -> Any: async with app_context: return await app_context.app.ensure_async(func)(*args, **kwargs) return wrapper
(func: Callable) -> Callable
29,465
quart.ctx
copy_current_request_context
Share the current request context with the function decorated. The request context is local per task and hence will not be available in any other task. This decorator can be used to make the context available, .. code-block:: python @copy_current_request_context async def within_context() -> None: method = request.method ...
def copy_current_request_context(func: Callable) -> Callable: """Share the current request context with the function decorated. The request context is local per task and hence will not be available in any other task. This decorator can be used to make the context available, .. code-block:: python @copy_current_request_context async def within_context() -> None: method = request.method ... """ if not has_request_context(): raise RuntimeError("Attempt to copy request context outside of a request context") request_context = _cv_request.get().copy() @wraps(func) async def wrapper(*args: Any, **kwargs: Any) -> Any: async with request_context: return await request_context.app.ensure_async(func)(*args, **kwargs) return wrapper
(func: Callable) -> Callable
29,466
quart.ctx
copy_current_websocket_context
Share the current websocket context with the function decorated. The websocket context is local per task and hence will not be available in any other task. This decorator can be used to make the context available, .. code-block:: python @copy_current_websocket_context async def within_context() -> None: method = websocket.method ...
def copy_current_websocket_context(func: Callable) -> Callable: """Share the current websocket context with the function decorated. The websocket context is local per task and hence will not be available in any other task. This decorator can be used to make the context available, .. code-block:: python @copy_current_websocket_context async def within_context() -> None: method = websocket.method ... """ if not has_websocket_context(): raise RuntimeError("Attempt to copy websocket context outside of a websocket context") websocket_context = _cv_websocket.get().copy() @wraps(func) async def wrapper(*args: Any, **kwargs: Any) -> Any: async with websocket_context: return await websocket_context.app.ensure_async(func)(*args, **kwargs) return wrapper
(func: Callable) -> Callable
29,470
quart.helpers
flash
Add a message (with optional category) to the session store. This is typically used to flash a message to a user that will be stored in the session and shown during some other request. For example, .. code-block:: python @app.route('/login', methods=['POST']) async def login(): ... await flash('Login successful') return redirect(url_for('index')) allows the index route to show the flashed messages, without having to accept the message as an argument or otherwise. See :func:`~quart.helpers.get_flashed_messages` for message retrieval.
def get_load_dotenv(default: bool = True) -> bool: """Get whether the user has disabled loading default dotenv files by setting :envvar:`QUART_SKIP_DOTENV`. The default is ``True``, load the files. :param default: What to return if the env var isn't set. """ val = os.environ.get("QUART_SKIP_DOTENV") if not val: return default return val.lower() in ("0", "false", "no")
(message: str, category: str = 'message') -> NoneType
29,472
quart.helpers
get_flashed_messages
Retrieve the flashed messages stored in the session. This is mostly useful in templates where it is exposed as a global function, for example .. code-block:: html+jinja <ul> {% for message in get_flashed_messages() %} <li>{{ message }}</li> {% endfor %} </ul> Note that caution is required for usage of ``category_filter`` as all messages will be popped, but only those matching the filter returned. See :func:`~quart.helpers.flash` for message creation.
def get_flashed_messages( with_categories: bool = False, category_filter: Iterable[str] = () ) -> list[str] | list[tuple[str, str]]: """Retrieve the flashed messages stored in the session. This is mostly useful in templates where it is exposed as a global function, for example .. code-block:: html+jinja <ul> {% for message in get_flashed_messages() %} <li>{{ message }}</li> {% endfor %} </ul> Note that caution is required for usage of ``category_filter`` as all messages will be popped, but only those matching the filter returned. See :func:`~quart.helpers.flash` for message creation. """ flashes = request_ctx.flashes if flashes is None: flashes = session.pop("_flashes") if "_flashes" in session else [] request_ctx.flashes = flashes if category_filter: flashes = [flash for flash in flashes if flash[0] in category_filter] if not with_categories: flashes = [flash[1] for flash in flashes] return flashes
(with_categories: bool = False, category_filter: Iterable[str] = ()) -> list[str] | list[tuple[str, str]]
29,473
quart.helpers
get_template_attribute
Load a attribute from a template. This is useful in Python code in order to use attributes in templates. Arguments: template_name: To load the attribute from. attribute: The attribute name to load
def get_template_attribute(template_name: str, attribute: str) -> Any: """Load a attribute from a template. This is useful in Python code in order to use attributes in templates. Arguments: template_name: To load the attribute from. attribute: The attribute name to load """ return getattr(current_app.jinja_env.get_template(template_name).module, attribute)
(template_name: str, attribute: str) -> Any
29,475
quart.ctx
has_app_context
Check if execution is within an app context. This allows a controlled way to act if there is an app context available, or silently not act if not. For example, .. code-block:: python if has_app_context(): log.info("Executing in %s context", current_app.name) See also :func:`has_request_context`
def has_app_context() -> bool: """Check if execution is within an app context. This allows a controlled way to act if there is an app context available, or silently not act if not. For example, .. code-block:: python if has_app_context(): log.info("Executing in %s context", current_app.name) See also :func:`has_request_context` """ return _cv_app.get(None) is not None
() -> bool
29,476
quart.ctx
has_request_context
Check if execution is within a request context. This allows a controlled way to act if there is a request context available, or silently not act if not. For example, .. code-block:: python if has_request_context(): log.info("Request endpoint %s", request.endpoint) See also :func:`has_app_context`.
def has_request_context() -> bool: """Check if execution is within a request context. This allows a controlled way to act if there is a request context available, or silently not act if not. For example, .. code-block:: python if has_request_context(): log.info("Request endpoint %s", request.endpoint) See also :func:`has_app_context`. """ return _cv_request.get(None) is not None
() -> bool
29,477
quart.ctx
has_websocket_context
Check if execution is within a websocket context. This allows a controlled way to act if there is a websocket context available, or silently not act if not. For example, .. code-block:: python if has_websocket_context(): log.info("Websocket endpoint %s", websocket.endpoint) See also :func:`has_app_context`.
def has_websocket_context() -> bool: """Check if execution is within a websocket context. This allows a controlled way to act if there is a websocket context available, or silently not act if not. For example, .. code-block:: python if has_websocket_context(): log.info("Websocket endpoint %s", websocket.endpoint) See also :func:`has_app_context`. """ return _cv_websocket.get(None) is not None
() -> bool
29,480
quart.json
jsonify
null
def jsonify(*args: Any, **kwargs: Any) -> Response: return current_app.json.response(*args, **kwargs) # type: ignore
(*args: 'Any', **kwargs: 'Any') -> 'Response'
29,481
quart.helpers
make_push_promise
Create a push promise, a simple wrapper function. This takes a path that should be pushed to the client if the protocol is HTTP/2.
def get_load_dotenv(default: bool = True) -> bool: """Get whether the user has disabled loading default dotenv files by setting :envvar:`QUART_SKIP_DOTENV`. The default is ``True``, load the files. :param default: What to return if the env var isn't set. """ val = os.environ.get("QUART_SKIP_DOTENV") if not val: return default return val.lower() in ("0", "false", "no")
(path: str) -> NoneType
29,482
quart.helpers
make_response
Create a response, a simple wrapper function. This is most useful when you want to alter a Response before returning it, for example .. code-block:: python response = make_response(render_template('index.html')) response.headers['X-Header'] = 'Something'
def get_load_dotenv(default: bool = True) -> bool: """Get whether the user has disabled loading default dotenv files by setting :envvar:`QUART_SKIP_DOTENV`. The default is ``True``, load the files. :param default: What to return if the env var isn't set. """ val = os.environ.get("QUART_SKIP_DOTENV") if not val: return default return val.lower() in ("0", "false", "no")
(*args: Any) -> Union[quart.wrappers.response.Response, werkzeug.wrappers.response.Response]
29,483
quart.helpers
redirect
Redirect to the location with the status code.
def redirect(location: str, code: int = 302) -> WerkzeugResponse: """Redirect to the location with the status code.""" if current_app: return current_app.redirect(location, code=code) return werkzeug_redirect(location, code=code)
(location: str, code: int = 302) -> werkzeug.wrappers.response.Response
29,484
quart.templating
render_template
Render the template with the context given. Arguments: template_name_or_list: Template name to render of a list of possible template names. context: The variables to pass to the template.
def __init__(self, app: Quart, **options: Any) -> None: """Create a Quart specific Jinja Environment. Arguments: app: The Quart app to bind to. options: The standard Jinja Environment options. """ if "loader" not in options: options["loader"] = app.create_global_jinja_loader() options["enable_async"] = True super().__init__(**options)
(template_name_or_list: str | list[str], **context: Any) -> str
29,485
quart.templating
render_template_string
Render the template source with the context given. Arguments: source: The template source code. context: The variables to pass to the template.
def __init__(self, app: Quart, **options: Any) -> None: """Create a Quart specific Jinja Environment. Arguments: app: The Quart app to bind to. options: The standard Jinja Environment options. """ if "loader" not in options: options["loader"] = app.create_global_jinja_loader() options["enable_async"] = True super().__init__(**options)
(source: str, **context: Any) -> str
29,487
quart.helpers
send_file
Return a Response to send the filename given. Arguments: filename_or_io: The filename (path) to send, remember to use :func:`safe_join`. mimetype: Mimetype to use, by default it will be guessed or revert to the DEFAULT_MIMETYPE. as_attachment: If true use the attachment filename in a Content-Disposition attachment header. attachment_filename: Name for the filename, if it differs add_etags: Set etags based on the filename, size and modification time. last_modified: Used to override the last modified value. cache_timeout: Time in seconds for the response to be cached.
def find_package(name: str) -> tuple[Path | None, Path]: """Finds packages install prefix (or None) and it's containing Folder""" module = name.split(".")[0] loader = pkgutil.get_loader(module) if name == "__main__" or loader is None: package_path = Path.cwd() else: if hasattr(loader, "get_filename"): filename = loader.get_filename(module) else: __import__(name) filename = sys.modules[name].__file__ package_path = Path(filename).resolve().parent if hasattr(loader, "is_package"): is_package = loader.is_package(module) if is_package: package_path = Path(package_path).resolve().parent sys_prefix = Path(sys.prefix).resolve() try: package_path.relative_to(sys_prefix) except ValueError: return None, package_path else: return sys_prefix, package_path
(filename_or_io: Union[bytes, str, os.PathLike, _io.BytesIO], mimetype: Optional[str] = None, as_attachment: bool = False, attachment_filename: Optional[str] = None, add_etags: bool = True, cache_timeout: Optional[int] = None, conditional: bool = False, last_modified: Optional[datetime.datetime] = None) -> quart.wrappers.response.Response
29,488
quart.helpers
send_from_directory
Send a file from a given directory. Arguments: directory: Directory that when combined with file_name gives the file path. file_name: File name that when combined with directory gives the file path. See :func:`send_file` for the other arguments.
def find_package(name: str) -> tuple[Path | None, Path]: """Finds packages install prefix (or None) and it's containing Folder""" module = name.split(".")[0] loader = pkgutil.get_loader(module) if name == "__main__" or loader is None: package_path = Path.cwd() else: if hasattr(loader, "get_filename"): filename = loader.get_filename(module) else: __import__(name) filename = sys.modules[name].__file__ package_path = Path(filename).resolve().parent if hasattr(loader, "is_package"): is_package = loader.is_package(module) if is_package: package_path = Path(package_path).resolve().parent sys_prefix = Path(sys.prefix).resolve() try: package_path.relative_to(sys_prefix) except ValueError: return None, package_path else: return sys_prefix, package_path
(directory: Union[bytes, str, os.PathLike], file_name: str, *, mimetype: Optional[str] = None, as_attachment: bool = False, attachment_filename: Optional[str] = None, add_etags: bool = True, cache_timeout: Optional[int] = None, conditional: bool = True, last_modified: Optional[datetime.datetime] = None) -> quart.wrappers.response.Response
29,491
quart.templating
stream_template
Render a template by name with the given context as a stream. This returns an iterator of strings, which can be used as a streaming response from a view. Arguments: template_name_or_list: The name of the template to render. If a list is given, the first name to exist will be rendered. context: The variables to make available in the template.
def __init__(self, app: Quart, **options: Any) -> None: """Create a Quart specific Jinja Environment. Arguments: app: The Quart app to bind to. options: The standard Jinja Environment options. """ if "loader" not in options: options["loader"] = app.create_global_jinja_loader() options["enable_async"] = True super().__init__(**options)
(template_name_or_list: str | jinja2.environment.Template | list[str | jinja2.environment.Template], **context: Any) -> AsyncIterator[str]
29,492
quart.templating
stream_template_string
Render a template from the given source with the *context* as a stream. This returns an iterator of strings, which can be used as a streaming response from a view. Arguments: source: The source code of the template to render. context: The variables to make available in the template.
def __init__(self, app: Quart, **options: Any) -> None: """Create a Quart specific Jinja Environment. Arguments: app: The Quart app to bind to. options: The standard Jinja Environment options. """ if "loader" not in options: options["loader"] = app.create_global_jinja_loader() options["enable_async"] = True super().__init__(**options)
(source: str, **context: Any) -> AsyncIterator[str]
29,493
quart.helpers
stream_with_context
Share the current request context with a generator. This allows the request context to be accessed within a streaming generator, for example, .. code-block:: python @app.route('/') def index() -> AsyncGenerator[bytes, None]: @stream_with_context async def generator() -> bytes: yield request.method.encode() yield b' ' yield request.path.encode() return generator()
def stream_with_context(func: Callable) -> Callable: """Share the current request context with a generator. This allows the request context to be accessed within a streaming generator, for example, .. code-block:: python @app.route('/') def index() -> AsyncGenerator[bytes, None]: @stream_with_context async def generator() -> bytes: yield request.method.encode() yield b' ' yield request.path.encode() return generator() """ request_context = _cv_request.get().copy() @wraps(func) async def generator(*args: Any, **kwargs: Any) -> Any: async with request_context: async for data in func(*args, **kwargs): yield data return generator
(func: Callable) -> Callable
29,497
quart.helpers
url_for
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.
def url_for( endpoint: str, *, _anchor: str | None = None, _external: bool | None = None, _method: str | None = None, _scheme: str | None = None, **values: Any, ) -> str: """Return the url for a specific endpoint. This is most useful in templates and redirects to create a URL that can be used in the browser. 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. """ return current_app.url_for( endpoint, _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external, **values, )
(endpoint: str, *, _anchor: Optional[str] = None, _external: Optional[bool] = None, _method: Optional[str] = None, _scheme: Optional[str] = None, **values: Any) -> str
29,500
eth_rlp.main
HashableRLP
An extension of :class:`rlp.Serializable`. In addition to the below functions, the class is iterable. Use like: :: class MyRLP(HashableRLP): fields = ( ('name1', rlp.sedes.big_endian_int), ('name2', rlp.sedes.binary), etc... ) my_obj = MyRLP(name2=b'\xff', name1=1) list(my_obj) == [1, b'\xff'] # note that the iteration order is always in RLP-defined order
class HashableRLP(rlp.Serializable): # type: ignore r""" An extension of :class:`rlp.Serializable`. In addition to the below functions, the class is iterable. Use like: :: class MyRLP(HashableRLP): fields = ( ('name1', rlp.sedes.big_endian_int), ('name2', rlp.sedes.binary), etc... ) my_obj = MyRLP(name2=b'\xff', name1=1) list(my_obj) == [1, b'\xff'] # note that the iteration order is always in RLP-defined order """ @classmethod def from_dict(cls, field_dict: Dict[str, Any]) -> Self: r""" In addition to the standard initialization of. :: my_obj = MyRLP(name1=1, name2=b'\xff') This method enables initialization with. :: my_obj = MyRLP.from_dict({'name1': 1, 'name2': b'\xff'}) In general, the standard initialization is preferred, but some approaches might favor this API, like when using :meth:`toolz.functoolz.pipe`. :: return eth_utils.toolz.pipe( my_dict, normalize, validate, MyRLP.from_dict, ) :param dict field_dict: the dictionary of values to initialize with :returns: the new rlp object :rtype: HashableRLP """ return cls(**field_dict) @classmethod def from_bytes(cls, serialized_bytes: Union[bytes, bytearray]) -> Self: """ Shorthand invocation for :meth:`rlp.decode` using this class. :param bytes serialized_bytes: the byte string to decode :return: the decoded object :rtype: HashableRLP """ decoded = rlp.decode(serialized_bytes, cls) return cast(Self, decoded) def hash(self) -> HexBytes: """ :returns: the hash of the encoded bytestring :rtype: ~hexbytes.main.HexBytes """ return pipe( self, rlp.encode, keccak, HexBytes, ) def __iter__(self) -> Any: if hasattr(self, "fields"): return iter(getattr(self, field) for field, _ in self.fields) else: return super().__iter__() def as_dict(self) -> Dict[str, Any]: """ Convert rlp object to a dict :returns: mapping of RLP field names to field values :rtype: dict """ try: _as_dict = super().as_dict() return cast(Dict[str, Any], _as_dict) except AttributeError: _as_dict = vars(self) return cast(Dict[str, Any], _as_dict)
(*args, **kwargs)
29,502
rlp.sedes.serializable
__copy__
null
def __copy__(self): return self.copy()
(self)
29,503
rlp.sedes.serializable
__deepcopy__
null
def __deepcopy__(self, *args): return self.copy()
(self, *args)
29,504
rlp.sedes.serializable
__eq__
null
def __eq__(self, other): return isinstance(other, Serializable) and hash(self) == hash(other)
(self, other)
29,505
rlp.sedes.serializable
__getitem__
null
def __getitem__(self, idx): if isinstance(idx, int): attr = self._meta.field_attrs[idx] return getattr(self, attr) elif isinstance(idx, slice): field_slice = self._meta.field_attrs[idx] return tuple(getattr(self, field) for field in field_slice) elif isinstance(idx, str): return getattr(self, idx) else: raise IndexError(f"Unsupported type for __getitem__: {type(idx)}")
(self, idx)
29,506
rlp.sedes.serializable
__getstate__
null
def __getstate__(self): state = self.__dict__.copy() # The hash() builtin is not stable across processes # (https://docs.python.org/3/reference/datamodel.html#object.__hash__), so we do # this here to ensure pickled instances don't carry the cached hash() as that # may cause issues like https://github.com/ethereum/py-evm/issues/1318 state["_hash_cache"] = None return state
(self)
29,507
rlp.sedes.serializable
__hash__
null
def __hash__(self): if self._hash_cache is None: self._hash_cache = hash(tuple(self)) return self._hash_cache
(self)
29,508
rlp.sedes.serializable
__init__
null
def __init__(self, *args, **kwargs): if kwargs: field_values = merge_kwargs_to_args(args, kwargs, self._meta.field_names) else: field_values = args if len(field_values) != len(self._meta.field_names): raise TypeError( f"Argument count mismatch. expected {len(self._meta.field_names)} - " f"got {len(field_values)} - " f"missing {','.join(self._meta.field_names[len(field_values) :])}" ) for value, attr in zip(field_values, self._meta.field_attrs): setattr(self, attr, make_immutable(value))
(self, *args, **kwargs)
29,509
eth_rlp.main
__iter__
null
def __iter__(self) -> Any: if hasattr(self, "fields"): return iter(getattr(self, field) for field, _ in self.fields) else: return super().__iter__()
(self) -> Any
29,510
rlp.sedes.serializable
__len__
null
def __len__(self): return len(self._meta.fields)
(self)
29,511
rlp.sedes.serializable
__repr__
null
def __repr__(self): keyword_args = tuple(f"{k}={v!r}" for k, v in self.as_dict().items()) return f"{type(self).__name__}({', '.join(keyword_args)})"
(self)
29,513
eth_rlp.main
as_dict
Convert rlp object to a dict :returns: mapping of RLP field names to field values :rtype: dict
def as_dict(self) -> Dict[str, Any]: """ Convert rlp object to a dict :returns: mapping of RLP field names to field values :rtype: dict """ try: _as_dict = super().as_dict() return cast(Dict[str, Any], _as_dict) except AttributeError: _as_dict = vars(self) return cast(Dict[str, Any], _as_dict)
(self) -> Dict[str, Any]
29,514
rlp.sedes.serializable
build_changeset
null
def build_changeset(self, *args, **kwargs): args_as_kwargs = merge_args_to_kwargs( args, kwargs, self._meta.field_names, allow_missing=True, ) return Changeset(self, changes=args_as_kwargs)
(self, *args, **kwargs)
29,515
rlp.sedes.serializable
copy
null
def copy(self, *args, **kwargs): missing_overrides = ( set(self._meta.field_names) .difference(kwargs.keys()) .difference(self._meta.field_names[: len(args)]) ) unchanged_kwargs = { key: copy.deepcopy(value) for key, value in self.as_dict().items() if key in missing_overrides } combined_kwargs = dict(**unchanged_kwargs, **kwargs) all_kwargs = merge_args_to_kwargs(args, combined_kwargs, self._meta.field_names) return type(self)(**all_kwargs)
(self, *args, **kwargs)
29,517
eth_rlp.main
hash
:returns: the hash of the encoded bytestring :rtype: ~hexbytes.main.HexBytes
def hash(self) -> HexBytes: """ :returns: the hash of the encoded bytestring :rtype: ~hexbytes.main.HexBytes """ return pipe( self, rlp.encode, keccak, HexBytes, )
(self) -> hexbytes.main.HexBytes
29,522
collections.abc
Coroutine
null
from collections.abc import Coroutine
()
29,524
collections.abc
close
Raise GeneratorExit inside coroutine.
null
(self)
29,525
collections.abc
send
Send a value into the coroutine. Return next yielded value or raise StopIteration.
null
(self, value)
29,526
collections.abc
throw
Raise an exception in the coroutine. Return next yielded value or raise StopIteration.
null
(self, typ, val=None, tb=None)