Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/aiohttp/web.py
7757 views
import asyncio1import logging2import socket3import sys4from argparse import ArgumentParser5from collections.abc import Iterable6from importlib import import_module7from typing import (8Any,9Awaitable,10Callable,11Iterable as TypingIterable,12List,13Optional,14Set,15Type,16Union,17cast,18)1920from .abc import AbstractAccessLogger21from .helpers import all_tasks22from .log import access_logger23from .web_app import Application as Application, CleanupError as CleanupError24from .web_exceptions import (25HTTPAccepted as HTTPAccepted,26HTTPBadGateway as HTTPBadGateway,27HTTPBadRequest as HTTPBadRequest,28HTTPClientError as HTTPClientError,29HTTPConflict as HTTPConflict,30HTTPCreated as HTTPCreated,31HTTPError as HTTPError,32HTTPException as HTTPException,33HTTPExpectationFailed as HTTPExpectationFailed,34HTTPFailedDependency as HTTPFailedDependency,35HTTPForbidden as HTTPForbidden,36HTTPFound as HTTPFound,37HTTPGatewayTimeout as HTTPGatewayTimeout,38HTTPGone as HTTPGone,39HTTPInsufficientStorage as HTTPInsufficientStorage,40HTTPInternalServerError as HTTPInternalServerError,41HTTPLengthRequired as HTTPLengthRequired,42HTTPMethodNotAllowed as HTTPMethodNotAllowed,43HTTPMisdirectedRequest as HTTPMisdirectedRequest,44HTTPMovedPermanently as HTTPMovedPermanently,45HTTPMultipleChoices as HTTPMultipleChoices,46HTTPNetworkAuthenticationRequired as HTTPNetworkAuthenticationRequired,47HTTPNoContent as HTTPNoContent,48HTTPNonAuthoritativeInformation as HTTPNonAuthoritativeInformation,49HTTPNotAcceptable as HTTPNotAcceptable,50HTTPNotExtended as HTTPNotExtended,51HTTPNotFound as HTTPNotFound,52HTTPNotImplemented as HTTPNotImplemented,53HTTPNotModified as HTTPNotModified,54HTTPOk as HTTPOk,55HTTPPartialContent as HTTPPartialContent,56HTTPPaymentRequired as HTTPPaymentRequired,57HTTPPermanentRedirect as HTTPPermanentRedirect,58HTTPPreconditionFailed as HTTPPreconditionFailed,59HTTPPreconditionRequired as HTTPPreconditionRequired,60HTTPProxyAuthenticationRequired as HTTPProxyAuthenticationRequired,61HTTPRedirection as HTTPRedirection,62HTTPRequestEntityTooLarge as HTTPRequestEntityTooLarge,63HTTPRequestHeaderFieldsTooLarge as HTTPRequestHeaderFieldsTooLarge,64HTTPRequestRangeNotSatisfiable as HTTPRequestRangeNotSatisfiable,65HTTPRequestTimeout as HTTPRequestTimeout,66HTTPRequestURITooLong as HTTPRequestURITooLong,67HTTPResetContent as HTTPResetContent,68HTTPSeeOther as HTTPSeeOther,69HTTPServerError as HTTPServerError,70HTTPServiceUnavailable as HTTPServiceUnavailable,71HTTPSuccessful as HTTPSuccessful,72HTTPTemporaryRedirect as HTTPTemporaryRedirect,73HTTPTooManyRequests as HTTPTooManyRequests,74HTTPUnauthorized as HTTPUnauthorized,75HTTPUnavailableForLegalReasons as HTTPUnavailableForLegalReasons,76HTTPUnprocessableEntity as HTTPUnprocessableEntity,77HTTPUnsupportedMediaType as HTTPUnsupportedMediaType,78HTTPUpgradeRequired as HTTPUpgradeRequired,79HTTPUseProxy as HTTPUseProxy,80HTTPVariantAlsoNegotiates as HTTPVariantAlsoNegotiates,81HTTPVersionNotSupported as HTTPVersionNotSupported,82)83from .web_fileresponse import FileResponse as FileResponse84from .web_log import AccessLogger85from .web_middlewares import (86middleware as middleware,87normalize_path_middleware as normalize_path_middleware,88)89from .web_protocol import (90PayloadAccessError as PayloadAccessError,91RequestHandler as RequestHandler,92RequestPayloadError as RequestPayloadError,93)94from .web_request import (95BaseRequest as BaseRequest,96FileField as FileField,97Request as Request,98)99from .web_response import (100ContentCoding as ContentCoding,101Response as Response,102StreamResponse as StreamResponse,103json_response as json_response,104)105from .web_routedef import (106AbstractRouteDef as AbstractRouteDef,107RouteDef as RouteDef,108RouteTableDef as RouteTableDef,109StaticDef as StaticDef,110delete as delete,111get as get,112head as head,113options as options,114patch as patch,115post as post,116put as put,117route as route,118static as static,119view as view,120)121from .web_runner import (122AppRunner as AppRunner,123BaseRunner as BaseRunner,124BaseSite as BaseSite,125GracefulExit as GracefulExit,126NamedPipeSite as NamedPipeSite,127ServerRunner as ServerRunner,128SockSite as SockSite,129TCPSite as TCPSite,130UnixSite as UnixSite,131)132from .web_server import Server as Server133from .web_urldispatcher import (134AbstractResource as AbstractResource,135AbstractRoute as AbstractRoute,136DynamicResource as DynamicResource,137PlainResource as PlainResource,138Resource as Resource,139ResourceRoute as ResourceRoute,140StaticResource as StaticResource,141UrlDispatcher as UrlDispatcher,142UrlMappingMatchInfo as UrlMappingMatchInfo,143View as View,144)145from .web_ws import (146WebSocketReady as WebSocketReady,147WebSocketResponse as WebSocketResponse,148WSMsgType as WSMsgType,149)150151__all__ = (152# web_app153"Application",154"CleanupError",155# web_exceptions156"HTTPAccepted",157"HTTPBadGateway",158"HTTPBadRequest",159"HTTPClientError",160"HTTPConflict",161"HTTPCreated",162"HTTPError",163"HTTPException",164"HTTPExpectationFailed",165"HTTPFailedDependency",166"HTTPForbidden",167"HTTPFound",168"HTTPGatewayTimeout",169"HTTPGone",170"HTTPInsufficientStorage",171"HTTPInternalServerError",172"HTTPLengthRequired",173"HTTPMethodNotAllowed",174"HTTPMisdirectedRequest",175"HTTPMovedPermanently",176"HTTPMultipleChoices",177"HTTPNetworkAuthenticationRequired",178"HTTPNoContent",179"HTTPNonAuthoritativeInformation",180"HTTPNotAcceptable",181"HTTPNotExtended",182"HTTPNotFound",183"HTTPNotImplemented",184"HTTPNotModified",185"HTTPOk",186"HTTPPartialContent",187"HTTPPaymentRequired",188"HTTPPermanentRedirect",189"HTTPPreconditionFailed",190"HTTPPreconditionRequired",191"HTTPProxyAuthenticationRequired",192"HTTPRedirection",193"HTTPRequestEntityTooLarge",194"HTTPRequestHeaderFieldsTooLarge",195"HTTPRequestRangeNotSatisfiable",196"HTTPRequestTimeout",197"HTTPRequestURITooLong",198"HTTPResetContent",199"HTTPSeeOther",200"HTTPServerError",201"HTTPServiceUnavailable",202"HTTPSuccessful",203"HTTPTemporaryRedirect",204"HTTPTooManyRequests",205"HTTPUnauthorized",206"HTTPUnavailableForLegalReasons",207"HTTPUnprocessableEntity",208"HTTPUnsupportedMediaType",209"HTTPUpgradeRequired",210"HTTPUseProxy",211"HTTPVariantAlsoNegotiates",212"HTTPVersionNotSupported",213# web_fileresponse214"FileResponse",215# web_middlewares216"middleware",217"normalize_path_middleware",218# web_protocol219"PayloadAccessError",220"RequestHandler",221"RequestPayloadError",222# web_request223"BaseRequest",224"FileField",225"Request",226# web_response227"ContentCoding",228"Response",229"StreamResponse",230"json_response",231# web_routedef232"AbstractRouteDef",233"RouteDef",234"RouteTableDef",235"StaticDef",236"delete",237"get",238"head",239"options",240"patch",241"post",242"put",243"route",244"static",245"view",246# web_runner247"AppRunner",248"BaseRunner",249"BaseSite",250"GracefulExit",251"ServerRunner",252"SockSite",253"TCPSite",254"UnixSite",255"NamedPipeSite",256# web_server257"Server",258# web_urldispatcher259"AbstractResource",260"AbstractRoute",261"DynamicResource",262"PlainResource",263"Resource",264"ResourceRoute",265"StaticResource",266"UrlDispatcher",267"UrlMappingMatchInfo",268"View",269# web_ws270"WebSocketReady",271"WebSocketResponse",272"WSMsgType",273# web274"run_app",275)276277278try:279from ssl import SSLContext280except ImportError: # pragma: no cover281SSLContext = Any # type: ignore[misc,assignment]282283HostSequence = TypingIterable[str]284285286async def _run_app(287app: Union[Application, Awaitable[Application]],288*,289host: Optional[Union[str, HostSequence]] = None,290port: Optional[int] = None,291path: Optional[str] = None,292sock: Optional[socket.socket] = None,293shutdown_timeout: float = 60.0,294keepalive_timeout: float = 75.0,295ssl_context: Optional[SSLContext] = None,296print: Callable[..., None] = print,297backlog: int = 128,298access_log_class: Type[AbstractAccessLogger] = AccessLogger,299access_log_format: str = AccessLogger.LOG_FORMAT,300access_log: Optional[logging.Logger] = access_logger,301handle_signals: bool = True,302reuse_address: Optional[bool] = None,303reuse_port: Optional[bool] = None,304) -> None:305# A internal functio to actually do all dirty job for application running306if asyncio.iscoroutine(app):307app = await app # type: ignore[misc]308309app = cast(Application, app)310311runner = AppRunner(312app,313handle_signals=handle_signals,314access_log_class=access_log_class,315access_log_format=access_log_format,316access_log=access_log,317keepalive_timeout=keepalive_timeout,318)319320await runner.setup()321322sites = [] # type: List[BaseSite]323324try:325if host is not None:326if isinstance(host, (str, bytes, bytearray, memoryview)):327sites.append(328TCPSite(329runner,330host,331port,332shutdown_timeout=shutdown_timeout,333ssl_context=ssl_context,334backlog=backlog,335reuse_address=reuse_address,336reuse_port=reuse_port,337)338)339else:340for h in host:341sites.append(342TCPSite(343runner,344h,345port,346shutdown_timeout=shutdown_timeout,347ssl_context=ssl_context,348backlog=backlog,349reuse_address=reuse_address,350reuse_port=reuse_port,351)352)353elif path is None and sock is None or port is not None:354sites.append(355TCPSite(356runner,357port=port,358shutdown_timeout=shutdown_timeout,359ssl_context=ssl_context,360backlog=backlog,361reuse_address=reuse_address,362reuse_port=reuse_port,363)364)365366if path is not None:367if isinstance(path, (str, bytes, bytearray, memoryview)):368sites.append(369UnixSite(370runner,371path,372shutdown_timeout=shutdown_timeout,373ssl_context=ssl_context,374backlog=backlog,375)376)377else:378for p in path:379sites.append(380UnixSite(381runner,382p,383shutdown_timeout=shutdown_timeout,384ssl_context=ssl_context,385backlog=backlog,386)387)388389if sock is not None:390if not isinstance(sock, Iterable):391sites.append(392SockSite(393runner,394sock,395shutdown_timeout=shutdown_timeout,396ssl_context=ssl_context,397backlog=backlog,398)399)400else:401for s in sock:402sites.append(403SockSite(404runner,405s,406shutdown_timeout=shutdown_timeout,407ssl_context=ssl_context,408backlog=backlog,409)410)411for site in sites:412await site.start()413414if print: # pragma: no branch415names = sorted(str(s.name) for s in runner.sites)416print(417"======== Running on {} ========\n"418"(Press CTRL+C to quit)".format(", ".join(names))419)420421# sleep forever by 1 hour intervals,422# on Windows before Python 3.8 wake up every 1 second to handle423# Ctrl+C smoothly424if sys.platform == "win32" and sys.version_info < (3, 8):425delay = 1426else:427delay = 3600428429while True:430await asyncio.sleep(delay)431finally:432await runner.cleanup()433434435def _cancel_tasks(436to_cancel: Set["asyncio.Task[Any]"], loop: asyncio.AbstractEventLoop437) -> None:438if not to_cancel:439return440441for task in to_cancel:442task.cancel()443444loop.run_until_complete(asyncio.gather(*to_cancel, return_exceptions=True))445446for task in to_cancel:447if task.cancelled():448continue449if task.exception() is not None:450loop.call_exception_handler(451{452"message": "unhandled exception during asyncio.run() shutdown",453"exception": task.exception(),454"task": task,455}456)457458459def run_app(460app: Union[Application, Awaitable[Application]],461*,462host: Optional[Union[str, HostSequence]] = None,463port: Optional[int] = None,464path: Optional[str] = None,465sock: Optional[socket.socket] = None,466shutdown_timeout: float = 60.0,467keepalive_timeout: float = 75.0,468ssl_context: Optional[SSLContext] = None,469print: Callable[..., None] = print,470backlog: int = 128,471access_log_class: Type[AbstractAccessLogger] = AccessLogger,472access_log_format: str = AccessLogger.LOG_FORMAT,473access_log: Optional[logging.Logger] = access_logger,474handle_signals: bool = True,475reuse_address: Optional[bool] = None,476reuse_port: Optional[bool] = None,477loop: Optional[asyncio.AbstractEventLoop] = None,478) -> None:479"""Run an app locally"""480if loop is None:481loop = asyncio.new_event_loop()482483# Configure if and only if in debugging mode and using the default logger484if loop.get_debug() and access_log and access_log.name == "aiohttp.access":485if access_log.level == logging.NOTSET:486access_log.setLevel(logging.DEBUG)487if not access_log.hasHandlers():488access_log.addHandler(logging.StreamHandler())489490main_task = loop.create_task(491_run_app(492app,493host=host,494port=port,495path=path,496sock=sock,497shutdown_timeout=shutdown_timeout,498keepalive_timeout=keepalive_timeout,499ssl_context=ssl_context,500print=print,501backlog=backlog,502access_log_class=access_log_class,503access_log_format=access_log_format,504access_log=access_log,505handle_signals=handle_signals,506reuse_address=reuse_address,507reuse_port=reuse_port,508)509)510511try:512asyncio.set_event_loop(loop)513loop.run_until_complete(main_task)514except (GracefulExit, KeyboardInterrupt): # pragma: no cover515pass516finally:517_cancel_tasks({main_task}, loop)518_cancel_tasks(all_tasks(loop), loop)519loop.run_until_complete(loop.shutdown_asyncgens())520loop.close()521522523def main(argv: List[str]) -> None:524arg_parser = ArgumentParser(525description="aiohttp.web Application server", prog="aiohttp.web"526)527arg_parser.add_argument(528"entry_func",529help=(530"Callable returning the `aiohttp.web.Application` instance to "531"run. Should be specified in the 'module:function' syntax."532),533metavar="entry-func",534)535arg_parser.add_argument(536"-H",537"--hostname",538help="TCP/IP hostname to serve on (default: %(default)r)",539default="localhost",540)541arg_parser.add_argument(542"-P",543"--port",544help="TCP/IP port to serve on (default: %(default)r)",545type=int,546default="8080",547)548arg_parser.add_argument(549"-U",550"--path",551help="Unix file system path to serve on. Specifying a path will cause "552"hostname and port arguments to be ignored.",553)554args, extra_argv = arg_parser.parse_known_args(argv)555556# Import logic557mod_str, _, func_str = args.entry_func.partition(":")558if not func_str or not mod_str:559arg_parser.error("'entry-func' not in 'module:function' syntax")560if mod_str.startswith("."):561arg_parser.error("relative module names not supported")562try:563module = import_module(mod_str)564except ImportError as ex:565arg_parser.error(f"unable to import {mod_str}: {ex}")566try:567func = getattr(module, func_str)568except AttributeError:569arg_parser.error(f"module {mod_str!r} has no attribute {func_str!r}")570571# Compatibility logic572if args.path is not None and not hasattr(socket, "AF_UNIX"):573arg_parser.error(574"file system paths not supported by your operating" " environment"575)576577logging.basicConfig(level=logging.DEBUG)578579app = func(extra_argv)580run_app(app, host=args.hostname, port=args.port, path=args.path)581arg_parser.exit(message="Stopped\n")582583584if __name__ == "__main__": # pragma: no branch585main(sys.argv[1:]) # pragma: no cover586587588