quart.flask_patch.app module

class quart.flask_patch.app.Quart(import_name: str, static_url_path: Optional[str] = None, static_folder: Optional[str] = 'static', static_host: Optional[str] = None, host_matching: bool = False, subdomain_matching: bool = False, template_folder: Optional[str] = 'templates', root_path: Optional[str] = None, instance_path: Optional[str] = None, instance_relative_config: bool = False)

Bases: quart.static.PackageStatic

The web framework class, handles requests and returns responses.

The primary method from a serving viewpoint is handle_request(), from an application viewpoint all the other methods are vital.

This can be extended in many ways, with most methods designed with this in mind. Additionally any of the classes listed as attributes can be replaced.

app_ctx_globals_class

The class to use for the g object

asgi_http_class

The class to use to handle the ASGI HTTP protocol.

asgi_lifespan_class

The class to use to handle the ASGI lifespan protocol.

asgi_websocket_class

The class to use to handle the ASGI websocket protocol.

config_class

The class to use for the configuration.

env

The name of the environment the app is running on.

debug

Wrapper around configuration DEBUG value, in many places this will result in more output if True. If unset, debug mode will be activated if environ is set to ‘development’.

jinja_environment

The class to use for the jinja environment.

jinja_options

The default options to set when creating the jinja environment.

json_decoder

The decoder for JSON data.

json_encoder

The encoder for JSON data.

permanent_session_lifetime

Wrapper around configuration PERMANENT_SESSION_LIFETIME value. Specifies how long the session data should survive.

request_class

The class to use for requests.

response_class

The class to user for responses.

secret_key

Warpper around configuration SECRET_KEY value. The app secret for signing sessions.

Wrapper around configuration SESSION_COOKIE_NAME, use to specify the cookie name for session data.

session_interface

The class to use as the session interface.

url_map_class

The class to map rules to endpoints.

url_rule_class

The class to use for URL rules.

websocket_class

The class to use for websockets.

add_template_filter(func: Callable, name: Optional[str] = None) → None

Add a template filter.

This is designed to be used on the application directly. An example usage,

def to_upper(value):
    return value.upper()

app.add_template_filter(to_upper)
Parameters
  • func – The function that is the filter.

  • name – The filter name (defaults to function name).

add_template_global(func: Callable, name: Optional[str] = None) → None

Add a template global.

This is designed to be used on the application directly. An example usage,

def five():
    return 5

app.add_template_global(five)
Parameters
  • func – The function that is the global.

  • name – The global name (defaults to function name).

add_template_test(func: Callable, name: Optional[str] = None) → None

Add a template test.

This is designed to be used on the application directly. An example usage,

def is_upper(value):
    return value.isupper()

app.add_template_test(is_upper)
Parameters
  • func – The function that is the test.

  • name – The test name (defaults to function name).

add_url_rule(path: str, endpoint: Optional[str] = None, view_func: Optional[Callable] = None, methods: Optional[Iterable[str]] = None, defaults: Optional[dict] = None, host: Optional[str] = None, subdomain: Optional[str] = None, *, provide_automatic_options: Optional[bool] = None, is_websocket: bool = False, strict_slashes: bool = True, merge_slashes: Optional[bool] = None) → None

Add a route/url rule to the application.

This is designed to be used on the application directly. An example usage,

def route():
    ...

app.add_url_rule('/', route)
Parameters
  • path – The path to route on, should start with a /.

  • func – Callable that returns a response.

  • methods – List of HTTP verbs the function routes.

  • endpoint – Optional endpoint name, if not present the function name is used.

  • defaults

    A dictionary of variables to provide automatically, use to provide a simpler default path for a route, e.g. to allow for /book rather than /book/0,

    @app.route('/book', defaults={'page': 0})
    @app.route('/book/<int:page>')
    def book(page):
        ...
    

  • host – The full host name for this route (should include subdomain if needed) - cannot be used with subdomain.

  • subdomain – A subdomain for this specific route.

  • provide_automatic_options – Optionally False to prevent OPTION handling.

  • strict_slashes – Strictly match the trailing slash present in the path. Will redirect a leaf (no slash) to a branch (with slash).

  • merge_slashes – Merge consecutive slashes to a single slash (unless as part of the path variable).

add_websocket(path: str, endpoint: Optional[str] = None, view_func: Optional[Callable] = None, defaults: Optional[dict] = None, host: Optional[str] = None, subdomain: Optional[str] = None, *, strict_slashes: bool = True) → None

Add a websocket url rule to the application.

This is designed to be used on the application directly. An example usage,

def websocket_route():
    ...

app.add_websocket('/', websocket_route)
Parameters
  • path – The path to route on, should start with a /.

  • func – Callable that returns a response.

  • endpoint – Optional endpoint name, if not present the function name is used.

  • defaults

    A dictionary of variables to provide automatically, use to provide a simpler default path for a route, e.g. to allow for /book rather than /book/0,

    @app.websocket('/book', defaults={'page': 0})
    @app.websocket('/book/<int:page>')
    def book(page):
        ...
    

  • host – The full host name for this route (should include subdomain if needed) - cannot be used with subdomain.

  • subdomain – A subdomain for this specific route.

  • strict_slashes – Strictly match the trailing slash present in the path. Will redirect a leaf (no slash) to a branch (with slash).

after_request(func: Union[Callable[[quart.wrappers.response.Response], quart.wrappers.response.Response], Callable[[quart.wrappers.response.Response], Awaitable[quart.wrappers.response.Response]]], name: Optional[str] = None) → Callable[[quart.wrappers.response.Response], Awaitable[None]]

Add an after request function.

This is designed to be used as a decorator, if used to decorate a synchronous function, the function will be wrapped in run_sync() and run in a thread executor (with the wrapped function returned). An example usage,

@app.after_request
async def func(response):
    return response
Parameters
  • func – The after request function itself.

  • name – Optional blueprint key name.

after_serving(func: Union[Callable[[], None], Callable[[], Awaitable[None]]]) → Callable[[], Awaitable[None]]

Add a after serving function.

This will allow the function provided to be called once after anything is served (after last byte is sent).

This is designed to be used as a decorator, if used to decorate a synchronous function, the function will be wrapped in run_sync() and run in a thread executor (with the wrapped function returned). An example usage,

@app.after_serving
async def func():
    ...
Parameters

func – The function itself.

after_websocket(func: Union[Callable[[quart.wrappers.response.Response], Optional[quart.wrappers.response.Response]], Callable[[quart.wrappers.response.Response], Awaitable[Optional[quart.wrappers.response.Response]]]], name: Optional[str] = None) → Callable[[quart.wrappers.response.Response], Awaitable[None]]

Add an after websocket function.

This is designed to be used as a decorator, if used to decorate a synchronous function, the function will be wrapped in run_sync() and run in a thread executor (with the wrapped function returned). An example usage,

@app.after_websocket
async def func(response):
    return response
Parameters
  • func – The after websocket function itself.

  • name – Optional blueprint key name.

app_context() → quart.ctx.AppContext

Create and return an app context.

This is best used within a context, i.e.

async with app.app_context():
    ...
app_ctx_globals_class

alias of quart.ctx._AppCtxGlobals

async asgi_app(scope: dict, receive: Callable, send: Callable) → None

This handles ASGI calls, it can be wrapped in middleware.

When using middleware with Quart it is preferable to wrap this method rather than the app itself. This is to ensure that the app is an instance of this class - which allows the quart cli to work correctly. To use this feature simply do,

app.asgi_app = middleware(app.asgi_app)
asgi_http_class

alias of quart.asgi.ASGIHTTPConnection

asgi_lifespan_class

alias of quart.asgi.ASGILifespan

asgi_websocket_class

alias of quart.asgi.ASGIWebsocketConnection

auto_find_instance_path() → pathlib.Path

Locates the instace_path if it was not provided

before_first_request(func: Union[Callable[[], None], Callable[[], Awaitable[None]]], name: Optional[str] = None) → Callable[[], Awaitable[None]]

Add a before first request function.

This is designed to be used as a decorator, if used to decorate a synchronous function, the function will be wrapped in run_sync() and run in a thread executor (with the wrapped function returned). An example usage,

@app.before_first_request
async def func():
    ...
Parameters
  • func – The before first request function itself.

  • name – Optional blueprint key name.

before_request(func: Union[Callable[[], None], Callable[[], Awaitable[None]]], name: Optional[str] = None) → Callable[[], Awaitable[None]]

Add a before request function.

This is designed to be used as a decorator, if used to decorate a synchronous function, the function will be wrapped in run_sync() and run in a thread executor (with the wrapped function returned). An example usage,

@app.before_request
async def func():
    ...
Parameters
  • func – The before request function itself.

  • name – Optional blueprint key name.

before_serving(func: Union[Callable[[], None], Callable[[], Awaitable[None]]]) → Callable[[], Awaitable[None]]

Add a before serving function.

This will allow the function provided to be called once before anything is served (before any byte is received).

This is designed to be used as a decorator, if used to decorate a synchronous function, the function will be wrapped in run_sync() and run in a thread executor (with the wrapped function returned). An example usage,

@app.before_serving
async def func():
    ...
Parameters

func – The function itself.

before_websocket(func: Union[Callable[[], None], Callable[[], Awaitable[None]]], name: Optional[str] = None) → Callable[[], Awaitable[None]]

Add a before websocket function.

This is designed to be used as a decorator, if used to decorate a synchronous function, the function will be wrapped in run_sync() and run in a thread executor (with the wrapped function returned). An example usage,

@app.before_websocket
async def func():
    ...
Parameters
  • func – The before websocket function itself.

  • name – Optional blueprint key name.

config_class

alias of quart.config.Config

context_processor(func: Union[Callable[[], Dict[str, Any]], Callable[[], Awaitable[Dict[str, Any]]]], name: Optional[str] = None) → Callable[[], Awaitable[Dict[str, Any]]]

Add a template context processor.

This is designed to be used as a decorator, if used to decorate a synchronous function, the function will be wrapped in run_sync() and run in a thread executor (with the wrapped function returned). An example usage,

@app.context_processor
async def update_context(context):
    return context
create_global_jinja_loader() → quart.templating.DispatchingJinjaLoader

Create and return a global (not blueprint specific) Jinja loader.

create_jinja_environment() → quart.templating.Environment

Create and return the jinja environment.

This will create the environment based on the jinja_options and configuration settings. The environment will include the Quart globals by default.

create_url_adapter(request: Optional[quart.wrappers.base.BaseRequestWebsocket]) → Optional[werkzeug.routing.MapAdapter]

Create and return a URL adapter.

This will create the adapter based on the request if present otherwise the app configuration.

debug

Implements a property descriptor for objects with a config attribute.

When used as a class instance it will look up the key on the class config object, for example:

class Object:
    config = {}
    foo = ConfigAttribute('foo')

obj = Object()
obj.foo = 'bob'
assert obj.foo == obj.config['foo']
async dispatch_request(request_context: Optional[quart.ctx.RequestContext] = None) → Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None], Tuple[Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], dict], Tuple[Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int], Tuple[Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int, dict]]

Dispatch the request to the view function.

Parameters

request_context – The request context, optional as Flask omits this argument.

async dispatch_websocket(websocket_context: Optional[quart.ctx.WebsocketContext] = None) → None

Dispatch the websocket to the view function.

Parameters

websocket_context – The websocket context, optional to match the Flask convention.

async do_teardown_appcontext(exc: Optional[BaseException]) → None

Teardown the app (context), calling the teardown functions.

async do_teardown_request(exc: Optional[BaseException], request_context: Optional[quart.ctx.RequestContext] = None) → None

Teardown the request, calling the teardown functions.

Parameters
  • exc – Any exception not handled that has caused the request to teardown.

  • request_context – The request context, optional as Flask omits this argument.

async do_teardown_websocket(exc: Optional[BaseException], websocket_context: Optional[quart.ctx.WebsocketContext] = None) → None

Teardown the websocket, calling the teardown functions.

Parameters
  • exc – Any exception not handled that has caused the websocket to teardown.

  • websocket_context – The websocket context, optional as Flask omits this argument.

endpoint(endpoint: str) → Callable

Register a function as an endpoint.

This is designed to be used as a decorator, if used to decorate a synchronous function, the function will be wrapped in run_sync() and run in a thread executor (with the wrapped function returned). An example usage,

@app.endpoint('name')
async def endpoint():
    ...
Parameters

endpoint – The endpoint name to use.

ensure_async(func: Callable[[...], Any]) → Callable[[...], Awaitable[Any]]

Ensure that the returned func is async and calls the func.

New in version 0.11.

Override if you wish to change how synchronous functions are run. Before Quart 0.11 this did not run the synchronous code in an executor.

env

Implements a property descriptor for objects with a config attribute.

When used as a class instance it will look up the key on the class config object, for example:

class Object:
    config = {}
    foo = ConfigAttribute('foo')

obj = Object()
obj.foo = 'bob'
assert obj.foo == obj.config['foo']
errorhandler(error: Union[Type[Exception], int]) → Callable

Register a function as an error handler.

This is designed to be used as a decorator. An example usage,

@app.errorhandler(500)
def error_handler():
    return "Error", 500
Parameters

error – The error code or Exception to handle.

async finalize_request(result: Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None], Tuple[Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], dict], Tuple[Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int], Tuple[Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int, dict]], request_context: Optional[quart.ctx.RequestContext] = None, from_error_handler: bool = False) → quart.wrappers.response.Response

Turns the view response return value into a response.

Parameters
  • result – The result of the request to finalize into a response.

  • request_context – The request context, optional as Flask omits this argument.

async finalize_websocket(result: Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None], Tuple[Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], dict], Tuple[Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int], Tuple[Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int, dict]], websocket_context: Optional[quart.ctx.WebsocketContext] = None, from_error_handler: bool = False) → Optional[quart.wrappers.response.Response]

Turns the view response return value into a response.

Parameters
  • result – The result of the websocket to finalize into a response.

  • websocket_context – The websocket context, optional as Flask omits this argument.

async full_dispatch_request(request_context: Optional[quart.ctx.RequestContext] = None) → quart.wrappers.response.Response

Adds pre and post processing to the request dispatching.

Parameters

request_context – The request context, optional as Flask omits this argument.

async full_dispatch_websocket(websocket_context: Optional[quart.ctx.WebsocketContext] = None) → Optional[quart.wrappers.response.Response]

Adds pre and post processing to the websocket dispatching.

Parameters

websocket_context – The websocket context, optional to match the Flask convention.

property got_first_request

Return if the app has received a request.

async handle_exception(error: Exception) → quart.wrappers.response.Response

Handle an uncaught exception.

By default this switches the error response to a 500 internal server error.

async handle_http_exception(error: Exception) → quart.wrappers.response.Response
async handle_request(request: quart.wrappers.request.Request) → quart.wrappers.response.Response
handle_url_build_error(error: Exception, endpoint: str, values: dict) → str

Handle a build error.

Ideally this will return a valid url given the error endpoint and values.

async handle_user_exception(error: Exception) → quart.wrappers.response.Response
async handle_websocket(websocket: quart.wrappers.request.Websocket) → Optional[quart.wrappers.response.Response]
async handle_websocket_exception(error: Exception) → Optional[quart.wrappers.response.Response]

Handle an uncaught exception.

By default this logs the exception and then re-raises it.

inject_url_defaults(endpoint: str, values: dict) → None

Injects default URL values into the passed values dict.

This is used to assist when building urls, see url_for().

iter_blueprints() → ValuesView[quart.blueprints.Blueprint]

Return a iterator over the blueprints.

property jinja_env

The jinja environment used to load templates.

jinja_environment

alias of quart.templating.Environment

jinja_options = {'autoescape': True, 'extensions': ['jinja2.ext.autoescape', 'jinja2.ext.with_']}
json_decoder

alias of quart.json.JSONDecoder

json_encoder

alias of quart.json.JSONEncoder

lock_class

alias of asyncio.locks.Lock

log_exception(exception_info: Tuple[type, BaseException, traceback]) → None

Log a exception to the logger.

By default this is only invoked for unhandled exceptions.

property logger

A logging.Logger logger for the app.

This can be used to log messages in a format as defined in the app configuration, for example,

app.logger.debug("Request method %s", request.method)
app.logger.error("Error, of some kind")
make_config(instance_relative: bool = False) → quart.config.Config

Create and return the configuration with appropriate defaults.

async make_default_options_response() → quart.wrappers.response.Response

This is the default route function for OPTIONS requests.

async make_null_session() → quart.sessions.Session

Create and return a null session.

async make_response(result: Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None], Tuple[Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], dict], Tuple[Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int], Tuple[Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int, dict]]) → quart.wrappers.response.Response

Make a Response from the result of the route handler.

The result itself can either be:
  • A Response object (or subclass).

  • A tuple of a ResponseValue and a header dictionary.

  • A tuple of a ResponseValue, status code and a header dictionary.

A ResponseValue is either a Response object (or subclass) or a str.

make_shell_context() → dict

Create a context for interactive shell usage.

The shell_context_processors can be used to add additional context.

property name

The name of this application.

This is taken from the import_name and is used for debugging purposes.

open_instance_resource(path: Union[bytes, str, os.PathLike], mode: str = 'rb') → IO[AnyStr]

Open a file for reading.

Use as

with app.open_instance_resouce(path) as file_:
    file_.read()
async open_session(request: quart.wrappers.base.BaseRequestWebsocket) → quart.sessions.Session

Open and return a Session using the request.

permanent_session_lifetime

Implements a property descriptor for objects with a config attribute.

When used as a class instance it will look up the key on the class config object, for example:

class Object:
    config = {}
    foo = ConfigAttribute('foo')

obj = Object()
obj.foo = 'bob'
assert obj.foo == obj.config['foo']
async postprocess_websocket(response: Optional[quart.wrappers.response.Response], websocket_context: Optional[quart.ctx.WebsocketContext] = None) → quart.wrappers.response.Response

Postprocess the websocket acting on the response.

Parameters
  • response – The response after the websocket is finalized.

  • webcoket_context – The websocket context, optional as Flask omits this argument.

async preprocess_request(request_context: Optional[quart.ctx.RequestContext] = None) → Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None], Tuple[Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], dict], Tuple[Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int], Tuple[Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int, dict], None]

Preprocess the request i.e. call before_request functions.

Parameters

request_context – The request context, optional as Flask omits this argument.

async preprocess_websocket(websocket_context: Optional[quart.ctx.WebsocketContext] = None) → Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None], Tuple[Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], dict], Tuple[Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int], Tuple[Union[Response, str, Dict[str, Any], AsyncGenerator[bytes, None], Generator[bytes, None, None]], int, dict], None]

Preprocess the websocket i.e. call before_websocket functions.

Parameters

websocket_context – The websocket context, optional as Flask omits this argument.

async process_response(response: quart.wrappers.response.Response, request_context: Optional[quart.ctx.RequestContext] = None) → quart.wrappers.response.Response

Postprocess the request acting on the response.

Parameters
  • response – The response after the request is finalized.

  • request_context – The request context, optional as Flask omits this argument.

property propagate_exceptions

Return true if exceptions should be propagated into debug pages.

If false the exception will be handled. See the PROPAGATE_EXCEPTIONS config settin.

register_blueprint(blueprint: quart.blueprints.Blueprint, url_prefix: Optional[str] = None) → None

Register a blueprint on the app.

This results in the blueprint’s routes, error handlers etc… being added to the app.

Parameters
  • blueprint – The blueprint to register.

  • url_prefix – Optional prefix to apply to all paths.

register_error_handler(error: Union[Type[Exception], int], func: Union[Callable[[Exception], None], Callable[[Exception], Awaitable[None]]], name: Optional[str] = None) → None

Register a function as an error handler.

This is designed to be used on the application directly. An example usage,

def error_handler():
    return "Error", 500

app.register_error_handler(500, error_handler)
Parameters
  • error – The error code or Exception to handle.

  • func – The function to handle the error.

  • name – Optional blueprint key name.

request_class

alias of quart.wrappers.request.Request

request_context(request: quart.wrappers.request.Request) → quart.ctx.RequestContext

Create and return a request context.

Use the test_request_context() whilst testing. This is best used within a context, i.e.

async with app.request_context(request):
    ...
Parameters

request – A request to build a context around.

response_class

alias of quart.wrappers.response.Response

route(path: str, methods: Optional[List[str]] = None, endpoint: Optional[str] = None, defaults: Optional[dict] = None, host: Optional[str] = None, subdomain: Optional[str] = None, *, provide_automatic_options: Optional[bool] = None, strict_slashes: bool = True) → Callable

Add a route to the application.

This is designed to be used as a decorator, if used to decorate a synchronous function, the function will be wrapped in run_sync() and run in a thread executor (with the wrapped function returned). An example usage,

@app.route('/')
async def route():
    ...
Parameters
  • path – The path to route on, should start with a /.

  • methods – List of HTTP verbs the function routes.

  • defaults

    A dictionary of variables to provide automatically, use to provide a simpler default path for a route, e.g. to allow for /book rather than /book/0,

    @app.route('/book', defaults={'page': 0})
    @app.route('/book/<int:page>')
    def book(page):
        ...
    

  • host – The full host name for this route (should include subdomain if needed) - cannot be used with subdomain.

  • subdomain – A subdomain for this specific route.

  • provide_automatic_options – Optionally False to prevent OPTION handling.

  • strict_slashes – Strictly match the trailing slash present in the path. Will redirect a leaf (no slash) to a branch (with slash).

run(host: str = '127.0.0.1', port: int = 5000, debug: Optional[bool] = None, use_reloader: bool = True, loop: Optional[asyncio.events.AbstractEventLoop] = None, ca_certs: Optional[str] = None, certfile: Optional[str] = None, keyfile: Optional[str] = None, **kwargs: Any) → None

Run this application.

This is best used for development only, see Hypercorn for production servers.

Parameters
  • host – Hostname to listen on. By default this is loopback only, use 0.0.0.0 to have the server listen externally.

  • port – Port number to listen on.

  • debug – If set enable (or disable) debug mode and debug output.

  • use_reloader – Automatically reload on code changes.

  • loop – Asyncio loop to create the server in, if None, take default one. If specified it is the caller’s responsibility to close and cleanup the loop.

  • ca_certs – Path to the SSL CA certificate file.

  • certfile – Path to the SSL certificate file.

  • keyfile – Path to the SSL key file.

run_task(host: str = '127.0.0.1', port: int = 5000, debug: Optional[bool] = None, use_reloader: bool = True, ca_certs: Optional[str] = None, certfile: Optional[str] = None, keyfile: Optional[str] = None, shutdown_trigger: Optional[Callable[[...], Awaitable[None]]] = None) → Coroutine[None, None, None]

Return a task that when awaited runs this application.

This is best used for development only, see Hypercorn for production servers.

Parameters
  • host – Hostname to listen on. By default this is loopback only, use 0.0.0.0 to have the server listen externally.

  • port – Port number to listen on.

  • debug – If set enable (or disable) debug mode and debug output.

  • use_reloader – Automatically reload on code changes.

  • 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.

async save_session(session: quart.sessions.Session, response: quart.wrappers.response.Response) → None

Saves the session to the response.

secret_key

Implements a property descriptor for objects with a config attribute.

When used as a class instance it will look up the key on the class config object, for example:

class Object:
    config = {}
    foo = ConfigAttribute('foo')

obj = Object()
obj.foo = 'bob'
assert obj.foo == obj.config['foo']
select_jinja_autoescape(filename: str) → bool

Returns True if the filename indicates that it should be escaped.

send_file_max_age_default

Implements a property descriptor for objects with a config attribute.

When used as a class instance it will look up the key on the class config object, for example:

class Object:
    config = {}
    foo = ConfigAttribute('foo')

obj = Object()
obj.foo = 'bob'
assert obj.foo == obj.config['foo']
session_cookie_name

Implements a property descriptor for objects with a config attribute.

When used as a class instance it will look up the key on the class config object, for example:

class Object:
    config = {}
    foo = ConfigAttribute('foo')

obj = Object()
obj.foo = 'bob'
assert obj.foo == obj.config['foo']
session_interface = <quart.sessions.SecureCookieSessionInterface object>
shell_context_processor(func: Callable[[], None]) → Callable

Add a shell context processor.

This is designed to be used as a decorator. An example usage,

@app.shell_context_processor
def additional_context():
    return context
async shutdown() → None
async startup() → None
teardown_appcontext(func: Union[Callable[[Optional[BaseException]], None], Callable[[Optional[BaseException]], Awaitable[None]]]) → Callable[[Optional[BaseException]], Awaitable[None]]

Add a teardown app (context) function.

This is designed to be used as a decorator, if used to decorate a synchronous function, the function will be wrapped in run_sync() and run in a thread executor (with the wrapped function returned). An example usage,

@app.teardown_appcontext
async def func():
    ...
Parameters
  • func – The teardown function itself.

  • name – Optional blueprint key name.

teardown_request(func: Union[Callable[[Optional[BaseException]], None], Callable[[Optional[BaseException]], Awaitable[None]]], name: Optional[str] = None) → Callable[[Optional[BaseException]], Awaitable[None]]

Add a teardown request function.

This is designed to be used as a decorator, if used to decorate a synchronous function, the function will be wrapped in run_sync() and run in a thread executor (with the wrapped function returned). An example usage,

@app.teardown_request
async def func():
    ...
Parameters
  • func – The teardown request function itself.

  • name – Optional blueprint key name.

teardown_websocket(func: Union[Callable[[Optional[BaseException]], None], Callable[[Optional[BaseException]], Awaitable[None]]], name: Optional[str] = None) → Callable[[Optional[BaseException]], Awaitable[None]]

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 run_sync() and run in a thread executor (with the wrapped function returned). An example usage,

@app.teardown_websocket
async def func():
    ...
Parameters
  • func – The teardown websocket function itself.

  • name – Optional blueprint key name.

template_filter(name: Optional[str] = None) → Callable

Add a template filter.

This is designed to be used as a decorator. An example usage,

@app.template_filter('name')
def to_upper(value):
    return value.upper()
Parameters

name – The filter name (defaults to function name).

template_global(name: Optional[str] = None) → Callable

Add a template global.

This is designed to be used as a decorator. An example usage,

@app.template_global('name')
def five():
    return 5
Parameters

name – The global name (defaults to function name).

template_test(name: Optional[str] = None) → Callable

Add a template test.

This is designed to be used as a decorator. An example usage,

@app.template_test('name')
def is_upper(value):
    return value.isupper()
Parameters

name – The test name (defaults to function name).

test_client() → quart.testing.QuartClient

Creates and returns a test client.

test_client_class

alias of quart.testing.QuartClient

test_request_context(path: str, *, method: str = 'GET', headers: Union[dict, werkzeug.datastructures.Headers, None] = None, query_string: Optional[dict] = None, scheme: str = 'http', send_push_promise: Callable[[str, werkzeug.datastructures.Headers], Awaitable[None]] = <function no_op_push>, data: Optional[AnyStr] = None, form: Optional[dict] = None, json: Any = <object object>, root_path: str = '', http_version: str = '1.1') → quart.ctx.RequestContext

Create a request context for testing purposes.

This is best used for testing code within request contexts. It is a simplified wrapper of request_context(). It is best used in a with block, i.e.

async with app.test_request_context("/", method="GET"):
    ...
Parameters
  • path – Request path.

  • method – HTTP verb

  • headers – Headers to include in the request.

  • query_string – To send as a dictionary, alternatively the query_string can be determined from the path.

  • scheme – Scheme for the request, default http.

testing

Implements a property descriptor for objects with a config attribute.

When used as a class instance it will look up the key on the class config object, for example:

class Object:
    config = {}
    foo = ConfigAttribute('foo')

obj = Object()
obj.foo = 'bob'
assert obj.foo == obj.config['foo']
trap_http_exception(error: Exception) → bool

Check it error is http and should be trapped.

Trapped errors are not handled by the handle_http_exception(), but instead trapped by the outer most (or user handlers). This can be useful when debuging to allow tracebacks to be viewed by the debug page.

async try_trigger_before_first_request_functions() → None

Trigger the before first request methods.

async update_template_context(context: dict) → None

Update the provided template context.

This adds additional context from the various template context processors.

Parameters

context – The context to update (mutate).

url_defaults(func: Callable, name: Optional[str] = None) → Callable

Add a url default preprocessor.

This is designed to be used as a decorator. An example usage,

@app.url_defaults
def default(endpoint, values):
    ...
url_map_class

alias of quart.routing.QuartMap

url_rule_class

alias of quart.routing.QuartRule

url_value_preprocessor(func: Callable[[str, dict], None], name: Optional[str] = None) → Callable

Add a url value preprocessor.

This is designed to be used as a decorator. An example usage,

@app.url_value_preprocessor
def value_preprocessor(endpoint, view_args):
    ...
websocket(path: str, endpoint: Optional[str] = None, defaults: Optional[dict] = None, host: Optional[str] = None, subdomain: Optional[str] = None, *, strict_slashes: bool = True) → Callable

Add a websocket to the application.

This is designed to be used as a decorator, if used to decorate a synchronous function, the function will be wrapped in run_sync() and run in a thread executor (with the wrapped function returned). An example usage,

@app.websocket('/')
async def websocket_route():
    ...
Parameters
  • path – The path to route on, should start with a /.

  • defaults

    A dictionary of variables to provide automatically, use to provide a simpler default path for a route, e.g. to allow for /book rather than /book/0,

    @app.websocket('/book', defaults={'page': 0})
    @app.websocket('/book/<int:page>')
    def book(page):
        ...
    

  • host – The full host name for this route (should include subdomain if needed) - cannot be used with subdomain.

  • subdomain – A subdomain for this specific route.

  • strict_slashes – Strictly match the trailing slash present in the path. Will redirect a leaf (no slash) to a branch (with slash).

websocket_class

alias of quart.wrappers.request.Websocket

websocket_context(websocket: quart.wrappers.request.Websocket) → quart.ctx.WebsocketContext

Create and return a websocket context.

Use the test_websocket_context() whilst testing. This is best used within a context, i.e.

async with app.websocket_context(websocket):
    ...
Parameters

websocket – A websocket to build a context around.