Skip to content

Commit

Permalink
Fix warning displayed by default (aio-libs#7677) (aio-libs#7752)
Browse files Browse the repository at this point in the history
Co-authored-by: pre-commit-ci[bot]
<66853113+pre-commit-ci[bot]@users.noreply.github.com>
(cherry picked from commit 32a1bae)
  • Loading branch information
Dreamsorcerer authored and Xiang Li committed Dec 4, 2023
1 parent 8ce5f72 commit c11de4e
Show file tree
Hide file tree
Showing 2 changed files with 332 additions and 186 deletions.
263 changes: 130 additions & 133 deletions aiohttp/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
import warnings
from argparse import ArgumentParser
from collections.abc import Iterable
from contextlib import suppress
from functools import partial
from importlib import import_module
from typing import (
Any,
Expand All @@ -21,122 +19,141 @@
Union,
cast,
)
from weakref import WeakSet

from .abc import AbstractAccessLogger
from .helpers import AppKey
from .helpers import AppKey as AppKey
from .log import access_logger
from .typedefs import PathLike
from .web_app import Application, CleanupError
from .web_app import Application as Application, CleanupError as CleanupError
from .web_exceptions import (
HTTPAccepted,
HTTPBadGateway,
HTTPBadRequest,
HTTPClientError,
HTTPConflict,
HTTPCreated,
HTTPError,
HTTPException,
HTTPExpectationFailed,
HTTPFailedDependency,
HTTPForbidden,
HTTPFound,
HTTPGatewayTimeout,
HTTPGone,
HTTPInsufficientStorage,
HTTPInternalServerError,
HTTPLengthRequired,
HTTPMethodNotAllowed,
HTTPMisdirectedRequest,
HTTPMove,
HTTPMovedPermanently,
HTTPMultipleChoices,
HTTPNetworkAuthenticationRequired,
HTTPNoContent,
HTTPNonAuthoritativeInformation,
HTTPNotAcceptable,
HTTPNotExtended,
HTTPNotFound,
HTTPNotImplemented,
HTTPNotModified,
HTTPOk,
HTTPPartialContent,
HTTPPaymentRequired,
HTTPPermanentRedirect,
HTTPPreconditionFailed,
HTTPPreconditionRequired,
HTTPProxyAuthenticationRequired,
HTTPRedirection,
HTTPRequestEntityTooLarge,
HTTPRequestHeaderFieldsTooLarge,
HTTPRequestRangeNotSatisfiable,
HTTPRequestTimeout,
HTTPRequestURITooLong,
HTTPResetContent,
HTTPSeeOther,
HTTPServerError,
HTTPServiceUnavailable,
HTTPSuccessful,
HTTPTemporaryRedirect,
HTTPTooManyRequests,
HTTPUnauthorized,
HTTPUnavailableForLegalReasons,
HTTPUnprocessableEntity,
HTTPUnsupportedMediaType,
HTTPUpgradeRequired,
HTTPUseProxy,
HTTPVariantAlsoNegotiates,
HTTPVersionNotSupported,
NotAppKeyWarning,
HTTPAccepted as HTTPAccepted,
HTTPBadGateway as HTTPBadGateway,
HTTPBadRequest as HTTPBadRequest,
HTTPClientError as HTTPClientError,
HTTPConflict as HTTPConflict,
HTTPCreated as HTTPCreated,
HTTPError as HTTPError,
HTTPException as HTTPException,
HTTPExpectationFailed as HTTPExpectationFailed,
HTTPFailedDependency as HTTPFailedDependency,
HTTPForbidden as HTTPForbidden,
HTTPFound as HTTPFound,
HTTPGatewayTimeout as HTTPGatewayTimeout,
HTTPGone as HTTPGone,
HTTPInsufficientStorage as HTTPInsufficientStorage,
HTTPInternalServerError as HTTPInternalServerError,
HTTPLengthRequired as HTTPLengthRequired,
HTTPMethodNotAllowed as HTTPMethodNotAllowed,
HTTPMisdirectedRequest as HTTPMisdirectedRequest,
HTTPMove as HTTPMove,
HTTPMovedPermanently as HTTPMovedPermanently,
HTTPMultipleChoices as HTTPMultipleChoices,
HTTPNetworkAuthenticationRequired as HTTPNetworkAuthenticationRequired,
HTTPNoContent as HTTPNoContent,
HTTPNonAuthoritativeInformation as HTTPNonAuthoritativeInformation,
HTTPNotAcceptable as HTTPNotAcceptable,
HTTPNotExtended as HTTPNotExtended,
HTTPNotFound as HTTPNotFound,
HTTPNotImplemented as HTTPNotImplemented,
HTTPNotModified as HTTPNotModified,
HTTPOk as HTTPOk,
HTTPPartialContent as HTTPPartialContent,
HTTPPaymentRequired as HTTPPaymentRequired,
HTTPPermanentRedirect as HTTPPermanentRedirect,
HTTPPreconditionFailed as HTTPPreconditionFailed,
HTTPPreconditionRequired as HTTPPreconditionRequired,
HTTPProxyAuthenticationRequired as HTTPProxyAuthenticationRequired,
HTTPRedirection as HTTPRedirection,
HTTPRequestEntityTooLarge as HTTPRequestEntityTooLarge,
HTTPRequestHeaderFieldsTooLarge as HTTPRequestHeaderFieldsTooLarge,
HTTPRequestRangeNotSatisfiable as HTTPRequestRangeNotSatisfiable,
HTTPRequestTimeout as HTTPRequestTimeout,
HTTPRequestURITooLong as HTTPRequestURITooLong,
HTTPResetContent as HTTPResetContent,
HTTPSeeOther as HTTPSeeOther,
HTTPServerError as HTTPServerError,
HTTPServiceUnavailable as HTTPServiceUnavailable,
HTTPSuccessful as HTTPSuccessful,
HTTPTemporaryRedirect as HTTPTemporaryRedirect,
HTTPTooManyRequests as HTTPTooManyRequests,
HTTPUnauthorized as HTTPUnauthorized,
HTTPUnavailableForLegalReasons as HTTPUnavailableForLegalReasons,
HTTPUnprocessableEntity as HTTPUnprocessableEntity,
HTTPUnsupportedMediaType as HTTPUnsupportedMediaType,
HTTPUpgradeRequired as HTTPUpgradeRequired,
HTTPUseProxy as HTTPUseProxy,
HTTPVariantAlsoNegotiates as HTTPVariantAlsoNegotiates,
HTTPVersionNotSupported as HTTPVersionNotSupported,
NotAppKeyWarning as NotAppKeyWarning,
)
from .web_fileresponse import FileResponse
from .web_fileresponse import FileResponse as FileResponse
from .web_log import AccessLogger
from .web_middlewares import middleware, normalize_path_middleware
from .web_protocol import PayloadAccessError, RequestHandler, RequestPayloadError
from .web_request import BaseRequest, FileField, Request
from .web_response import ContentCoding, Response, StreamResponse, json_response
from .web_middlewares import (
middleware as middleware,
normalize_path_middleware as normalize_path_middleware,
)
from .web_protocol import (
PayloadAccessError as PayloadAccessError,
RequestHandler as RequestHandler,
RequestPayloadError as RequestPayloadError,
)
from .web_request import (
BaseRequest as BaseRequest,
FileField as FileField,
Request as Request,
)
from .web_response import (
ContentCoding as ContentCoding,
Response as Response,
StreamResponse as StreamResponse,
json_response as json_response,
)
from .web_routedef import (
AbstractRouteDef,
RouteDef,
RouteTableDef,
StaticDef,
delete,
get,
head,
options,
patch,
post,
put,
route,
static,
view,
AbstractRouteDef as AbstractRouteDef,
RouteDef as RouteDef,
RouteTableDef as RouteTableDef,
StaticDef as StaticDef,
delete as delete,
get as get,
head as head,
options as options,
patch as patch,
post as post,
put as put,
route as route,
static as static,
view as view,
)
from .web_runner import (
AppRunner,
BaseRunner,
BaseSite,
GracefulExit,
NamedPipeSite,
ServerRunner,
SockSite,
TCPSite,
UnixSite,
AppRunner as AppRunner,
BaseRunner as BaseRunner,
BaseSite as BaseSite,
GracefulExit as GracefulExit,
NamedPipeSite as NamedPipeSite,
ServerRunner as ServerRunner,
SockSite as SockSite,
TCPSite as TCPSite,
UnixSite as UnixSite,
)
from .web_server import Server
from .web_server import Server as Server
from .web_urldispatcher import (
AbstractResource,
AbstractRoute,
DynamicResource,
PlainResource,
PrefixedSubAppResource,
Resource,
ResourceRoute,
StaticResource,
UrlDispatcher,
UrlMappingMatchInfo,
View,
AbstractResource as AbstractResource,
AbstractRoute as AbstractRoute,
DynamicResource as DynamicResource,
PlainResource as PlainResource,
PrefixedSubAppResource as PrefixedSubAppResource,
Resource as Resource,
ResourceRoute as ResourceRoute,
StaticResource as StaticResource,
UrlDispatcher as UrlDispatcher,
UrlMappingMatchInfo as UrlMappingMatchInfo,
View as View,
)
from .web_ws import (
WebSocketReady as WebSocketReady,
WebSocketResponse as WebSocketResponse,
WSMsgType as WSMsgType,
)
from .web_ws import WebSocketReady, WebSocketResponse, WSMsgType

__all__ = (
# web_app
Expand Down Expand Up @@ -300,24 +317,7 @@ async def _run_app(
reuse_port: Optional[bool] = None,
handler_cancellation: bool = False,
) -> None:
async def wait(
starting_tasks: "WeakSet[asyncio.Task[object]]", shutdown_timeout: float
) -> None:
# Wait for pending tasks for a given time limit.
t = asyncio.current_task()
assert t is not None
starting_tasks.add(t)
with suppress(asyncio.TimeoutError):
await asyncio.wait_for(_wait(starting_tasks), timeout=shutdown_timeout)

async def _wait(exclude: "WeakSet[asyncio.Task[object]]") -> None:
t = asyncio.current_task()
assert t is not None
exclude.add(t)
while tasks := asyncio.all_tasks().difference(exclude):
await asyncio.wait(tasks)

# An internal function to actually do all dirty job for application running
# A internal functio to actually do all dirty job for application running
if asyncio.iscoroutine(app):
app = await app

Expand All @@ -330,17 +330,10 @@ async def _wait(exclude: "WeakSet[asyncio.Task[object]]") -> None:
access_log_format=access_log_format,
access_log=access_log,
keepalive_timeout=keepalive_timeout,
shutdown_timeout=shutdown_timeout,
handler_cancellation=handler_cancellation,
)

await runner.setup()
# On shutdown we want to avoid waiting on tasks which run forever.
# It's very likely that all tasks which run forever will have been created by
# the time we have completed the application startup (in runner.setup()),
# so we just record all running tasks here and exclude them later.
starting_tasks: "WeakSet[asyncio.Task[object]]" = WeakSet(asyncio.all_tasks())
runner.shutdown_callback = partial(wait, starting_tasks, shutdown_timeout)

sites: List[BaseSite] = []

Expand All @@ -352,6 +345,7 @@ async def _wait(exclude: "WeakSet[asyncio.Task[object]]") -> None:
runner,
host,
port,
shutdown_timeout=shutdown_timeout,
ssl_context=ssl_context,
backlog=backlog,
reuse_address=reuse_address,
Expand All @@ -365,6 +359,7 @@ async def _wait(exclude: "WeakSet[asyncio.Task[object]]") -> None:
runner,
h,
port,
shutdown_timeout=shutdown_timeout,
ssl_context=ssl_context,
backlog=backlog,
reuse_address=reuse_address,
Expand All @@ -376,6 +371,7 @@ async def _wait(exclude: "WeakSet[asyncio.Task[object]]") -> None:
TCPSite(
runner,
port=port,
shutdown_timeout=shutdown_timeout,
ssl_context=ssl_context,
backlog=backlog,
reuse_address=reuse_address,
Expand All @@ -389,6 +385,7 @@ async def _wait(exclude: "WeakSet[asyncio.Task[object]]") -> None:
UnixSite(
runner,
path,
shutdown_timeout=shutdown_timeout,
ssl_context=ssl_context,
backlog=backlog,
)
Expand All @@ -399,6 +396,7 @@ async def _wait(exclude: "WeakSet[asyncio.Task[object]]") -> None:
UnixSite(
runner,
p,
shutdown_timeout=shutdown_timeout,
ssl_context=ssl_context,
backlog=backlog,
)
Expand All @@ -410,6 +408,7 @@ async def _wait(exclude: "WeakSet[asyncio.Task[object]]") -> None:
SockSite(
runner,
sock,
shutdown_timeout=shutdown_timeout,
ssl_context=ssl_context,
backlog=backlog,
)
Expand All @@ -420,6 +419,7 @@ async def _wait(exclude: "WeakSet[asyncio.Task[object]]") -> None:
SockSite(
runner,
s,
shutdown_timeout=shutdown_timeout,
ssl_context=ssl_context,
backlog=backlog,
)
Expand Down Expand Up @@ -468,7 +468,6 @@ def _cancel_tasks(
def run_app(
app: Union[Application, Awaitable[Application]],
*,
debug: bool = False,
host: Optional[Union[str, HostSequence]] = None,
port: Optional[int] = None,
path: Union[PathLike, TypingIterable[PathLike], None] = None,
Expand All @@ -490,7 +489,6 @@ def run_app(
"""Run an app locally"""
if loop is None:
loop = asyncio.new_event_loop()
loop.set_debug(debug)

# Configure if and only if in debugging mode and using the default logger
if loop.get_debug() and access_log and access_log.name == "aiohttp.access":
Expand Down Expand Up @@ -531,7 +529,6 @@ def run_app(
_cancel_tasks(asyncio.all_tasks(loop), loop)
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()
asyncio.set_event_loop(None)


def main(argv: List[str]) -> None:
Expand Down
Loading

0 comments on commit c11de4e

Please sign in to comment.