| 1 |
import sys |
| 2 |
import warnings |
| 3 |
from typing import Any, Awaitable, Callable, Coroutine, Optional, ParamSpec, TypeVar, Union |
| 4 |
|
| 5 |
import trio |
| 6 |
from hypercorn.config import Config as HyperConfig |
| 7 |
from hypercorn.trio import serve |
| 8 |
from quart import Quart, request_started, websocket_started |
| 9 |
from quart.ctx import AppContext |
| 10 |
from quart.signals import got_serving_exception |
| 11 |
from quart.typing import FilePath, ResponseReturnValue, ResponseTypes |
| 12 |
from quart.utils import file_path_to_path |
| 13 |
from quart.wrappers import Request, Websocket |
| 14 |
from werkzeug.exceptions import HTTPException |
| 15 |
|
| 16 |
from .asgi import TrioASGIHTTPConnection, TrioASGILifespan, TrioASGIWebsocketConnection |
| 17 |
from .testing import TrioClient, TrioTestApp |
| 18 |
from .utils import run_sync |
| 19 |
from .wrappers import TrioRequest, TrioResponse, TrioWebsocket |
| 20 |
|
| 21 |
T = TypeVar("T") |
| 22 |
P = ParamSpec("P") |
| 23 |
|
| 24 |
|
| 25 |
class QuartTrio(Quart): |
| 26 |
nursery: trio.Nursery |
| 27 |
asgi_http_class = TrioASGIHTTPConnection |
| 28 |
asgi_lifespan_class = TrioASGILifespan |
| 29 |
asgi_websocket_class = TrioASGIWebsocketConnection |
| 30 |
event_class = trio.Event # type: ignore |
| 31 |
lock_class = trio.Lock # type: ignore |
| 32 |
request_class = TrioRequest |
| 33 |
response_class = TrioResponse |
| 34 |
test_app_class = TrioTestApp |
| 35 |
test_client_class = TrioClient # type: ignore |
| 36 |
websocket_class = TrioWebsocket |
| 37 |
|
| 38 |
def run( # type: ignore |
| 39 |
self, |
| 40 |
host: str = "127.0.0.1", |
| 41 |
port: int = 5000, |
| 42 |
debug: Optional[bool] = None, |
| 43 |
use_reloader: bool = True, |
| 44 |
ca_certs: Optional[str] = None, |
| 45 |
certfile: Optional[str] = None, |
| 46 |
keyfile: Optional[str] = None, |
| 47 |
**kwargs: Any, |
| 48 |
) -> None: |
| 49 |
"""Run this application. |
| 50 |
|
| 51 |
This is best used for development only, see using Gunicorn for |
| 52 |
production servers. |
| 53 |
|
| 54 |
Arguments: |
| 55 |
host: Hostname to listen on. By default this is loopback |
| 56 |
only, use 0.0.0.0 to have the server listen externally. |
| 57 |
port: Port number to listen on. |
| 58 |
debug: If set enable (or disable) debug mode and debug output. |
| 59 |
use_reloader: Automatically reload on code changes. |
| 60 |
ca_certs: Path to the SSL CA certificate file. |
| 61 |
certfile: Path to the SSL certificate file. |
| 62 |
ciphers: Ciphers to use for the SSL setup. |
| 63 |
keyfile: Path to the SSL key file. |
| 64 |
""" |
| 65 |
if kwargs: |
| 66 |
warnings.warn( |
| 67 |
f"Additional arguments, {','.join(kwargs.keys())}, are not supported.\n" |
| 68 |
"They may be supported by Hypercorn, which is the ASGI server Quart " |
| 69 |
"uses by default. This method is meant for development and debugging." |
| 70 |
) |
| 71 |
|
| 72 |
scheme = "https" if certfile is not None and keyfile is not None else "http" |
| 73 |
print(f"Running on {scheme}://{host}:{port} (CTRL + C to quit)") # noqa: T201 |
| 74 |
|
| 75 |
trio.run(self.run_task, host, port, debug, ca_certs, certfile, keyfile) |
| 76 |
|
| 77 |
def run_task( |
| 78 |
self, |
| 79 |
host: str = "127.0.0.1", |
| 80 |
port: int = 5000, |
| 81 |
debug: Optional[bool] = None, |
| 82 |
ca_certs: Optional[str] = None, |
| 83 |
certfile: Optional[str] = None, |
| 84 |
keyfile: Optional[str] = None, |
| 85 |
shutdown_trigger: Optional[Callable[..., Awaitable[None]]] = None, |
| 86 |
task_status: trio.TaskStatus = trio.TASK_STATUS_IGNORED, |
| 87 |
) -> Coroutine[None, None, None]: |
| 88 |
"""Return a task that when awaited runs this application. |
| 89 |
|
| 90 |
This is best used for development only, see Hypercorn for |
| 91 |
production servers. |
| 92 |
|
| 93 |
Arguments: |
| 94 |
host: Hostname to listen on. By default this is loopback |
| 95 |
only, use 0.0.0.0 to have the server listen externally. |
| 96 |
port: Port number to listen on. |
| 97 |
debug: If set enable (or disable) debug mode and debug output. |
| 98 |
use_reloader: Automatically reload on code changes. |
| 99 |
loop: Asyncio loop to create the server in, if None, take default one. |
| 100 |
If specified it is the caller's responsibility to close and cleanup the |
| 101 |
loop. |
| 102 |
ca_certs: Path to the SSL CA certificate file. |
| 103 |
certfile: Path to the SSL certificate file. |
| 104 |
keyfile: Path to the SSL key file. |
| 105 |
|
| 106 |
""" |
| 107 |
config = HyperConfig() |
| 108 |
config.access_log_format = "%(h)s %(r)s %(s)s %(b)s %(D)s" |
| 109 |
config.accesslog = "-" |
| 110 |
config.bind = [f"{host}:{port}"] |
| 111 |
config.ca_certs = ca_certs |
| 112 |
config.certfile = certfile |
| 113 |
if debug is not None: |
| 114 |
config.debug = debug |
| 115 |
config.errorlog = config.accesslog |
| 116 |
config.keyfile = keyfile |
| 117 |
|
| 118 |
return serve( |
| 119 |
self, config, shutdown_trigger=shutdown_trigger, task_status=task_status # type: ignore |
| 120 |
) |
| 121 |
|
| 122 |
def sync_to_async(self, func: Callable[P, T]) -> Callable[P, Awaitable[T]]: |
| 123 |
"""Return a async function that will run the synchronous function *func*. |
| 124 |
|
| 125 |
This can be used as so,:: |
| 126 |
|
| 127 |
result = await app.sync_to_async(func)(*args, **kwargs) |
| 128 |
|
| 129 |
Override this method to change how the app converts sync code |
| 130 |
to be asynchronously callable. |
| 131 |
""" |
| 132 |
return run_sync(func) |
| 133 |
|
| 134 |
async def handle_request(self, request: Request) -> ResponseTypes: |
| 135 |
async with self.request_context(request) as ctx: |
| 136 |
try: |
| 137 |
return await self.full_dispatch_request(ctx) |
| 138 |
except trio.Cancelled: |
| 139 |
raise # Cancelled should be handled by serving code. |
| 140 |
except BaseExceptionGroup as error: |
| 141 |
filtered_error, _ = error.split(trio.Cancelled) |
| 142 |
if filtered_error is not None: |
| 143 |
raise filtered_error |
| 144 |
|
| 145 |
return await self.handle_exception(ctx, error) # type: ignore |
| 146 |
except Exception as error: |
| 147 |
return await self.handle_exception(ctx, error) |
| 148 |
finally: |
| 149 |
if request.scope.get("_quart._preserve_context", False): |
| 150 |
self._preserved_context = ctx.copy() |
| 151 |
|
| 152 |
async def full_dispatch_request(self, ctx: AppContext) -> ResponseTypes: |
| 153 |
"""Adds pre and post processing to the request dispatching. |
| 154 |
|
| 155 |
Arguments: |
| 156 |
request_context: The context containing the request. |
| 157 |
""" |
| 158 |
try: |
| 159 |
await request_started.send_async(self, _sync_wrapper=self.ensure_async) # type: ignore |
| 160 |
|
| 161 |
result: ResponseReturnValue | HTTPException | None |
| 162 |
result = await self.preprocess_request(ctx) |
| 163 |
if result is None: |
| 164 |
result = await self.dispatch_request(ctx) |
| 165 |
except (Exception, BaseExceptionGroup) as error: |
| 166 |
result = await self.handle_user_exception(ctx, error) |
| 167 |
return await self.finalize_request(ctx, result) |
| 168 |
|
| 169 |
async def handle_user_exception( |
| 170 |
self, ctx: AppContext, error: Union[Exception, BaseExceptionGroup] |
| 171 |
) -> Union[HTTPException, ResponseReturnValue]: |
| 172 |
if isinstance(error, BaseExceptionGroup): |
| 173 |
for exception in error.exceptions: |
| 174 |
try: |
| 175 |
return await self.handle_user_exception(ctx, exception) # type: ignore |
| 176 |
except Exception: |
| 177 |
pass # No handler for this error |
| 178 |
# Not found a single handler, re-raise the error |
| 179 |
raise error |
| 180 |
else: |
| 181 |
return await super().handle_user_exception(ctx, error) |
| 182 |
|
| 183 |
async def handle_websocket(self, websocket: Websocket) -> ResponseTypes | None: |
| 184 |
async with self.websocket_context(websocket) as ctx: |
| 185 |
try: |
| 186 |
return await self.full_dispatch_websocket(ctx) |
| 187 |
except trio.Cancelled: |
| 188 |
raise # Cancelled should be handled by serving code. |
| 189 |
except BaseExceptionGroup as error: |
| 190 |
filtered_error, _ = error.split(trio.Cancelled) |
| 191 |
if filtered_error is not None: |
| 192 |
raise filtered_error |
| 193 |
|
| 194 |
return await self.handle_websocket_exception(ctx, error) # type: ignore |
| 195 |
except Exception as error: |
| 196 |
return await self.handle_websocket_exception(ctx, error) |
| 197 |
finally: |
| 198 |
if websocket.scope.get("_quart._preserve_context", False): |
| 199 |
self._preserved_context = ctx.copy() |
| 200 |
|
| 201 |
async def full_dispatch_websocket(self, ctx: AppContext) -> ResponseTypes: |
| 202 |
"""Adds pre and post processing to the websocket dispatching. |
| 203 |
|
| 204 |
Arguments: |
| 205 |
websocket_context: The context containing the websocket. |
| 206 |
""" |
| 207 |
try: |
| 208 |
await websocket_started.send_async( |
| 209 |
self, _sync_wrapper=self.ensure_async # type: ignore |
| 210 |
) |
| 211 |
|
| 212 |
result: ResponseReturnValue | HTTPException | None |
| 213 |
result = await self.preprocess_websocket(ctx) |
| 214 |
if result is None: |
| 215 |
result = await self.dispatch_websocket(ctx) |
| 216 |
except (Exception, BaseExceptionGroup) as error: |
| 217 |
result = await self.handle_user_exception(ctx, error) |
| 218 |
return await self.finalize_websocket(ctx, result) |
| 219 |
|
| 220 |
async def open_instance_resource( |
| 221 |
self, path: FilePath, mode: str = "rb" |
| 222 |
) -> trio._file_io.AsyncIOWrapper: |
| 223 |
"""Open a file for reading. |
| 224 |
|
| 225 |
Use as |
| 226 |
|
| 227 |
.. code-block:: python |
| 228 |
|
| 229 |
async with await app.open_instance_resource(path) as file_: |
| 230 |
await file_.read() |
| 231 |
""" |
| 232 |
return await trio.open_file(self.instance_path / file_path_to_path(path), mode) |
| 233 |
|
| 234 |
async def open_resource(self, path: FilePath, mode: str = "rb") -> trio._file_io.AsyncIOWrapper: |
| 235 |
"""Open a file for reading. |
| 236 |
|
| 237 |
Use as |
| 238 |
|
| 239 |
.. code-block:: python |
| 240 |
|
| 241 |
async with await app.open_resource(path) as file_: |
| 242 |
await file_.read() |
| 243 |
""" |
| 244 |
if mode not in {"r", "rb"}: |
| 245 |
raise ValueError("Files can only be opened for reading") |
| 246 |
|
| 247 |
return await trio.open_file(self.root_path / file_path_to_path(path), mode) |
| 248 |
|
| 249 |
def add_background_task(self, func: Callable, *args: Any, **kwargs: Any) -> None: |
| 250 |
async def _wrapper() -> None: |
| 251 |
async with self.app_context() as ctx: |
| 252 |
try: |
| 253 |
await self.ensure_async(func)(*args, **kwargs) |
| 254 |
except (BaseExceptionGroup, Exception) as error: |
| 255 |
await self.handle_background_exception(ctx, error) # type: ignore |
| 256 |
|
| 257 |
self.nursery.start_soon(_wrapper) |
| 258 |
|
| 259 |
async def shutdown(self) -> None: |
| 260 |
if self.config["BACKGROUND_TASK_SHUTDOWN_TIMEOUT"] is not None: |
| 261 |
self.nursery.cancel_scope.deadline = ( |
| 262 |
trio.current_time() + self.config["BACKGROUND_TASK_SHUTDOWN_TIMEOUT"] |
| 263 |
) |
| 264 |
else: |
| 265 |
self.nursery.cancel_scope.cancel() |
| 266 |
|
| 267 |
async with self.app_context() as ctx: |
| 268 |
try: |
| 269 |
for gen in reversed(self.while_serving_gens): |
| 270 |
try: |
| 271 |
await gen.__anext__() |
| 272 |
except StopAsyncIteration: |
| 273 |
pass |
| 274 |
else: |
| 275 |
raise RuntimeError("While serving generator didn't terminate") |
| 276 |
for func in self.after_serving_funcs: |
| 277 |
await self.ensure_async(func)() |
| 278 |
except Exception as error: |
| 279 |
await got_serving_exception.send_async( |
| 280 |
self, _sync_wrapper=self.ensure_async, exception=error # type: ignore |
| 281 |
) |
| 282 |
self.log_exception(ctx, sys.exc_info()) |
| 283 |
raise |