From e4071c50ab95b34b423d3af98dab51f897db165b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tin=20Tvrtkovi=C4=87?= Date: Sun, 12 Nov 2023 16:40:17 +0100 Subject: [PATCH] AiohttpApp.run refactor --- CHANGELOG.md | 1 + src/uapi/aiohttp.py | 29 +++++++++++++++++++---------- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e16cdd8..063e97d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,7 @@ The **third number** is for emergencies when we need to start branches for older - OpenAPI `operationId` properties for operations are now generated from handler names. - OpenAPI summaries and descriptions are now supported, and can be overridden. - `aiohttp.web.StreamResponse` is now handled as the root class of aiohttp responses. +- {meth}`uapi.aiohttp.AiohttpApp.run` now uses the [aiohttp App runners](https://docs.aiohttp.org/en/stable/web_advanced.html#application-runners) internally. - _uapi_ is now tested against Flask 3. - _uapi_ is now tested against Python 3.12. diff --git a/src/uapi/aiohttp.py b/src/uapi/aiohttp.py index 9c3e977..a8dbfbb 100644 --- a/src/uapi/aiohttp.py +++ b/src/uapi/aiohttp.py @@ -3,11 +3,12 @@ from inspect import Parameter, Signature, signature from logging import Logger from typing import Any, ClassVar, TypeAlias, TypeVar +from asyncio import sleep -from aiohttp.web import Request as FrameworkRequest -from aiohttp.web import Response, RouteTableDef +from aiohttp.web import Request as FrameworkRequest, AppRunner +from aiohttp.web import Response, RouteTableDef, TCPSite from aiohttp.web import StreamResponse as FrameworkResponse -from aiohttp.web import _run_app, access_logger +from aiohttp.web import access_logger from aiohttp.web_app import Application from attrs import Factory, define from cattrs import Converter @@ -229,20 +230,28 @@ async def run( handle_signals: bool = True, shutdown_timeout: float = 60, access_log: Logger | None = access_logger, - print: Callable[..., None] | None = print, + handler_cancellation: bool = False, ): + """Start serving this app. + + If `handle_signals` is `False`, cancel the task running this to shut down. + + :param handle_signals: Whether to let the underlying server handle signals. + """ app = Application() app.add_routes(self.to_framework_routes()) - - await _run_app( + runner = AppRunner( app, - port=port, - host=host, handle_signals=handle_signals, - shutdown_timeout=shutdown_timeout, access_log=access_log, - print=print, + handler_cancellation=handler_cancellation, ) + await runner.setup() + site = TCPSite(runner, host, port, shutdown_timeout=shutdown_timeout) + await site.start() + + while True: + await sleep(3600) App: TypeAlias = AiohttpApp