A Python ASGI web framework with the same API as Flask
npx @tessl/cli install tessl/pypi-quart@0.20.00
# Quart
1
2
A 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.
3
4
## Package Information
5
6
- **Package Name**: quart
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install quart`
10
11
## Core Imports
12
13
```python
14
from quart import Quart, request, jsonify, render_template
15
```
16
17
For comprehensive import (includes all public components):
18
19
```python
20
from quart import *
21
```
22
23
Common patterns:
24
25
```python
26
from quart import Quart, Blueprint, request, websocket, jsonify
27
from quart import render_template, redirect, url_for, flash
28
```
29
30
## Basic Usage
31
32
```python
33
from quart import Quart, request, jsonify
34
35
app = Quart(__name__)
36
37
# HTTP route
38
@app.route('/')
39
async def hello():
40
return 'Hello, World!'
41
42
# HTTP route with JSON response
43
@app.route('/api/data')
44
async def get_data():
45
return jsonify({'message': 'Hello from Quart!', 'status': 'success'})
46
47
# HTTP route with request data
48
@app.route('/api/submit', methods=['POST'])
49
async def submit_data():
50
json_data = await request.get_json()
51
return jsonify({'received': json_data})
52
53
# WebSocket endpoint
54
@app.websocket('/ws')
55
async def ws():
56
await websocket.accept()
57
while True:
58
data = await websocket.receive()
59
await websocket.send(f"Echo: {data}")
60
61
if __name__ == '__main__':
62
app.run()
63
```
64
65
## Architecture
66
67
Quart's architecture closely mirrors Flask while providing full async/await support:
68
69
- **Application**: Central `Quart` class manages routes, configuration, and ASGI integration
70
- **Request/Response System**: Async-compatible wrappers around HTTP requests and responses
71
- **Context Management**: Application, request, and WebSocket contexts with proxy objects
72
- **Blueprint System**: Modular application organization with Flask-compatible API
73
- **WebSocket Support**: Native async WebSocket handling alongside HTTP routes
74
- **Signal System**: Event-driven hooks for application lifecycle management
75
76
This design enables easy migration from Flask applications while providing enhanced performance through asynchronous programming patterns and full ASGI compliance.
77
78
## Capabilities
79
80
### Core Application Framework
81
82
Central application class, modular blueprints, and configuration management for building scalable async web applications.
83
84
```python { .api }
85
class Quart:
86
def __init__(self, import_name: str, static_url_path: str | None = None, **kwargs): ...
87
def route(self, rule: str, **options): ...
88
def websocket(self, rule: str, **options): ...
89
def add_url_rule(self, rule: str, endpoint: str | None = None, view_func: Callable | None = None, **options): ...
90
def register_blueprint(self, blueprint: Blueprint, **options): ...
91
def errorhandler(self, code_or_exception): ...
92
def before_request(self, func): ...
93
def after_request(self, func): ...
94
async def run_task(self, host: str = "127.0.0.1", port: int = 5000, **kwargs): ...
95
96
class Blueprint:
97
def __init__(self, name: str, import_name: str, **kwargs): ...
98
def route(self, rule: str, **options): ...
99
def websocket(self, rule: str, **options): ...
100
101
class Config(dict):
102
def from_object(self, obj): ...
103
def from_pyfile(self, filename: str, silent: bool = False): ...
104
```
105
106
[Core Application Framework](./core-application.md)
107
108
### Request and Response System
109
110
Async HTTP request/response handling with form data, JSON processing, file uploads, and comprehensive header management.
111
112
```python { .api }
113
class Request:
114
method: str
115
path: str
116
args: ImmutableMultiDict
117
headers: Headers
118
async def get_json(self, force: bool = False, silent: bool = False, cache: bool = True): ...
119
async def get_data(self, cache: bool = True, as_text: bool = False): ...
120
121
class Response:
122
status_code: int
123
headers: Headers
124
data: bytes
125
def set_cookie(self, key: str, value: str = "", **kwargs): ...
126
127
class FileStorage:
128
filename: str | None
129
content_type: str | None
130
async def save(self, dst: str, buffer_size: int = 16384): ...
131
```
132
133
[Request and Response System](./request-response.md)
134
135
### WebSocket Support
136
137
Native async WebSocket connection handling with JSON message support and connection lifecycle management.
138
139
```python { .api }
140
class Websocket:
141
path: str
142
args: ImmutableMultiDict
143
headers: Headers
144
async def accept(self, headers: dict | Headers | None = None, subprotocol: str | None = None): ...
145
async def receive(self): ...
146
async def send(self, data): ...
147
async def receive_json(self): ...
148
async def send_json(self, *args, **kwargs): ...
149
async def close(self, code: int, reason: str = ""): ...
150
```
151
152
[WebSocket Support](./websocket.md)
153
154
### Template System
155
156
Async Jinja2 template rendering with streaming support and Flask-compatible template context.
157
158
```python { .api }
159
async def render_template(template_name_or_list: str, **context) -> str: ...
160
async def render_template_string(source: str, **context) -> str: ...
161
async def stream_template(template_name_or_list: str, **context): ...
162
async def stream_template_string(source: str, **context): ...
163
```
164
165
[Template System](./templates.md)
166
167
### Helper Functions and Utilities
168
169
HTTP helpers, URL generation, file serving, flash messaging, and advanced features for comprehensive web development.
170
171
```python { .api }
172
def abort(code: int, *args, **kwargs) -> NoReturn: ...
173
async def make_response(*args) -> Response: ...
174
def redirect(location: str, code: int = 302, Response=None) -> Response: ...
175
def url_for(endpoint: str, **values) -> str: ...
176
async def send_file(filename_or_io, mimetype: str | None = None, **kwargs) -> Response: ...
177
async def flash(message: str, category: str = "message"): ...
178
def get_flashed_messages(with_categories: bool = False, category_filter=()) -> list: ...
179
def jsonify(*args, **kwargs) -> Response: ...
180
```
181
182
[Helper Functions and Utilities](./helpers.md)
183
184
### Context Management
185
186
Application, request, and WebSocket context handling with global proxy objects and context copying utilities.
187
188
```python { .api }
189
def has_app_context() -> bool: ...
190
def has_request_context() -> bool: ...
191
def has_websocket_context() -> bool: ...
192
def copy_current_app_context(func): ...
193
def copy_current_request_context(func): ...
194
def after_this_request(func): ...
195
196
# Global proxy objects
197
current_app: Quart
198
request: Request
199
websocket: Websocket
200
session: dict
201
g: object
202
```
203
204
[Context Management](./context.md)
205
206
### Signal System
207
208
Event-driven hooks for application lifecycle, request/response processing, WebSocket handling, and error management.
209
210
```python { .api }
211
# Application lifecycle signals
212
appcontext_pushed: Namespace
213
appcontext_popped: Namespace
214
appcontext_tearing_down: Namespace
215
216
# Request lifecycle signals
217
request_started: Namespace
218
request_finished: Namespace
219
request_tearing_down: Namespace
220
221
# WebSocket lifecycle signals
222
websocket_started: Namespace
223
websocket_finished: Namespace
224
websocket_tearing_down: Namespace
225
226
# Template and exception signals
227
before_render_template: Namespace
228
template_rendered: Namespace
229
got_request_exception: Namespace
230
got_websocket_exception: Namespace
231
message_flashed: Namespace
232
```
233
234
[Signal System](./signals.md)
235
236
### Testing Framework
237
238
Comprehensive testing tools for HTTP routes, WebSocket connections, and CLI commands with async support.
239
240
```python { .api }
241
class QuartClient:
242
async def get(self, path: str, **kwargs): ...
243
async def post(self, path: str, **kwargs): ...
244
async def put(self, path: str, **kwargs): ...
245
async def delete(self, path: str, **kwargs): ...
246
async def websocket(self, path: str, **kwargs): ...
247
248
class QuartCliRunner:
249
def invoke(self, cli, args=None, **kwargs): ...
250
251
class TestApp(Quart):
252
def test_client(self, **kwargs) -> QuartClient: ...
253
def test_cli_runner(self, **kwargs) -> QuartCliRunner: ...
254
```
255
256
[Testing Framework](./testing.md)
257
258
## Types
259
260
```python { .api }
261
# Response types (from typing.py)
262
ResponseValue = Union[
263
Response,
264
WerkzeugResponse,
265
bytes,
266
str,
267
Mapping[str, Any], # any jsonify-able dict
268
list[Any], # any jsonify-able list
269
Iterator[bytes],
270
Iterator[str],
271
]
272
273
ResponseReturnValue = Union[
274
ResponseValue,
275
tuple[ResponseValue, HeadersValue],
276
tuple[ResponseValue, StatusCode],
277
tuple[ResponseValue, StatusCode, HeadersValue],
278
]
279
280
# Header types
281
HeaderName = str
282
HeaderValue = Union[str, list[str], tuple[str, ...]]
283
HeadersValue = Union[
284
Headers,
285
Mapping[HeaderName, HeaderValue],
286
Sequence[tuple[HeaderName, HeaderValue]],
287
]
288
289
# Callable types with both sync/async support
290
RouteCallable = Union[
291
Callable[..., ResponseReturnValue],
292
Callable[..., Awaitable[ResponseReturnValue]],
293
]
294
WebsocketCallable = Union[
295
Callable[..., Optional[ResponseReturnValue]],
296
Callable[..., Awaitable[Optional[ResponseReturnValue]]],
297
]
298
BeforeRequestCallable = Union[
299
Callable[[], Optional[ResponseReturnValue]],
300
Callable[[], Awaitable[Optional[ResponseReturnValue]]],
301
]
302
AfterRequestCallable = Union[
303
Callable[[ResponseTypes], ResponseTypes],
304
Callable[[ResponseTypes], Awaitable[ResponseTypes]],
305
]
306
ErrorHandlerCallable = Union[
307
Callable[[Any], ResponseReturnValue],
308
Callable[[Any], Awaitable[ResponseReturnValue]],
309
]
310
311
# Utility types
312
FilePath = Union[bytes, str, os.PathLike]
313
StatusCode = int
314
ResponseTypes = Union[Response, WerkzeugResponse]
315
316
# Optional types for advanced usage
317
AppOrBlueprintKey = Optional[str]
318
TeardownCallable = Union[
319
Callable[[Optional[BaseException]], None],
320
Callable[[Optional[BaseException]], Awaitable[None]],
321
]
322
```