A Python ASGI web framework with the same API as Flask
npx @tessl/cli install tessl/pypi-quart@0.20.0A Python ASGI web framework with the same API as Flask, designed for building modern asynchronous web applications. Quart provides Flask-compatible APIs while leveraging async/await for high-performance asynchronous operations, WebSocket support, and seamless integration with the ASGI ecosystem.
pip install quartfrom quart import Quart, request, jsonify, render_templateFor comprehensive import (includes all public components):
from quart import *Common patterns:
from quart import Quart, Blueprint, request, websocket, jsonify
from quart import render_template, redirect, url_for, flashfrom quart import Quart, request, jsonify
app = Quart(__name__)
# HTTP route
@app.route('/')
async def hello():
return 'Hello, World!'
# HTTP route with JSON response
@app.route('/api/data')
async def get_data():
return jsonify({'message': 'Hello from Quart!', 'status': 'success'})
# HTTP route with request data
@app.route('/api/submit', methods=['POST'])
async def submit_data():
json_data = await request.get_json()
return jsonify({'received': json_data})
# WebSocket endpoint
@app.websocket('/ws')
async def ws():
await websocket.accept()
while True:
data = await websocket.receive()
await websocket.send(f"Echo: {data}")
if __name__ == '__main__':
app.run()Quart's architecture closely mirrors Flask while providing full async/await support:
Quart class manages routes, configuration, and ASGI integrationThis design enables easy migration from Flask applications while providing enhanced performance through asynchronous programming patterns and full ASGI compliance.
Central application class, modular blueprints, and configuration management for building scalable async web applications.
class Quart:
def __init__(self, import_name: str, static_url_path: str | None = None, **kwargs): ...
def route(self, rule: str, **options): ...
def websocket(self, rule: str, **options): ...
def add_url_rule(self, rule: str, endpoint: str | None = None, view_func: Callable | None = None, **options): ...
def register_blueprint(self, blueprint: Blueprint, **options): ...
def errorhandler(self, code_or_exception): ...
def before_request(self, func): ...
def after_request(self, func): ...
async def run_task(self, host: str = "127.0.0.1", port: int = 5000, **kwargs): ...
class Blueprint:
def __init__(self, name: str, import_name: str, **kwargs): ...
def route(self, rule: str, **options): ...
def websocket(self, rule: str, **options): ...
class Config(dict):
def from_object(self, obj): ...
def from_pyfile(self, filename: str, silent: bool = False): ...Async HTTP request/response handling with form data, JSON processing, file uploads, and comprehensive header management.
class Request:
method: str
path: str
args: ImmutableMultiDict
headers: Headers
async def get_json(self, force: bool = False, silent: bool = False, cache: bool = True): ...
async def get_data(self, cache: bool = True, as_text: bool = False): ...
class Response:
status_code: int
headers: Headers
data: bytes
def set_cookie(self, key: str, value: str = "", **kwargs): ...
class FileStorage:
filename: str | None
content_type: str | None
async def save(self, dst: str, buffer_size: int = 16384): ...Native async WebSocket connection handling with JSON message support and connection lifecycle management.
class Websocket:
path: str
args: ImmutableMultiDict
headers: Headers
async def accept(self, headers: dict | Headers | None = None, subprotocol: str | None = None): ...
async def receive(self): ...
async def send(self, data): ...
async def receive_json(self): ...
async def send_json(self, *args, **kwargs): ...
async def close(self, code: int, reason: str = ""): ...Async Jinja2 template rendering with streaming support and Flask-compatible template context.
async def render_template(template_name_or_list: str, **context) -> str: ...
async def render_template_string(source: str, **context) -> str: ...
async def stream_template(template_name_or_list: str, **context): ...
async def stream_template_string(source: str, **context): ...HTTP helpers, URL generation, file serving, flash messaging, and advanced features for comprehensive web development.
def abort(code: int, *args, **kwargs) -> NoReturn: ...
async def make_response(*args) -> Response: ...
def redirect(location: str, code: int = 302, Response=None) -> Response: ...
def url_for(endpoint: str, **values) -> str: ...
async def send_file(filename_or_io, mimetype: str | None = None, **kwargs) -> Response: ...
async def flash(message: str, category: str = "message"): ...
def get_flashed_messages(with_categories: bool = False, category_filter=()) -> list: ...
def jsonify(*args, **kwargs) -> Response: ...Helper Functions and Utilities
Application, request, and WebSocket context handling with global proxy objects and context copying utilities.
def has_app_context() -> bool: ...
def has_request_context() -> bool: ...
def has_websocket_context() -> bool: ...
def copy_current_app_context(func): ...
def copy_current_request_context(func): ...
def after_this_request(func): ...
# Global proxy objects
current_app: Quart
request: Request
websocket: Websocket
session: dict
g: objectEvent-driven hooks for application lifecycle, request/response processing, WebSocket handling, and error management.
# Application lifecycle signals
appcontext_pushed: Namespace
appcontext_popped: Namespace
appcontext_tearing_down: Namespace
# Request lifecycle signals
request_started: Namespace
request_finished: Namespace
request_tearing_down: Namespace
# WebSocket lifecycle signals
websocket_started: Namespace
websocket_finished: Namespace
websocket_tearing_down: Namespace
# Template and exception signals
before_render_template: Namespace
template_rendered: Namespace
got_request_exception: Namespace
got_websocket_exception: Namespace
message_flashed: NamespaceComprehensive testing tools for HTTP routes, WebSocket connections, and CLI commands with async support.
class QuartClient:
async def get(self, path: str, **kwargs): ...
async def post(self, path: str, **kwargs): ...
async def put(self, path: str, **kwargs): ...
async def delete(self, path: str, **kwargs): ...
async def websocket(self, path: str, **kwargs): ...
class QuartCliRunner:
def invoke(self, cli, args=None, **kwargs): ...
class TestApp(Quart):
def test_client(self, **kwargs) -> QuartClient: ...
def test_cli_runner(self, **kwargs) -> QuartCliRunner: ...# Response types (from typing.py)
ResponseValue = Union[
Response,
WerkzeugResponse,
bytes,
str,
Mapping[str, Any], # any jsonify-able dict
list[Any], # any jsonify-able list
Iterator[bytes],
Iterator[str],
]
ResponseReturnValue = Union[
ResponseValue,
tuple[ResponseValue, HeadersValue],
tuple[ResponseValue, StatusCode],
tuple[ResponseValue, StatusCode, HeadersValue],
]
# Header types
HeaderName = str
HeaderValue = Union[str, list[str], tuple[str, ...]]
HeadersValue = Union[
Headers,
Mapping[HeaderName, HeaderValue],
Sequence[tuple[HeaderName, HeaderValue]],
]
# Callable types with both sync/async support
RouteCallable = Union[
Callable[..., ResponseReturnValue],
Callable[..., Awaitable[ResponseReturnValue]],
]
WebsocketCallable = Union[
Callable[..., Optional[ResponseReturnValue]],
Callable[..., Awaitable[Optional[ResponseReturnValue]]],
]
BeforeRequestCallable = Union[
Callable[[], Optional[ResponseReturnValue]],
Callable[[], Awaitable[Optional[ResponseReturnValue]]],
]
AfterRequestCallable = Union[
Callable[[ResponseTypes], ResponseTypes],
Callable[[ResponseTypes], Awaitable[ResponseTypes]],
]
ErrorHandlerCallable = Union[
Callable[[Any], ResponseReturnValue],
Callable[[Any], Awaitable[ResponseReturnValue]],
]
# Utility types
FilePath = Union[bytes, str, os.PathLike]
StatusCode = int
ResponseTypes = Union[Response, WerkzeugResponse]
# Optional types for advanced usage
AppOrBlueprintKey = Optional[str]
TeardownCallable = Union[
Callable[[Optional[BaseException]], None],
Callable[[Optional[BaseException]], Awaitable[None]],
]