Debian Codegraph @

third_party/python/aiohttp/aiohttp/web.py

raw
1 import asyncio
2 import logging
3 import os
4 import socket
5 import sys
6 import warnings
7 from argparse import ArgumentParser
8 from collections.abc import Iterable
9 from contextlib import suppress
10 from importlib import import_module
11 from typing import (
12 Any,
13 Awaitable,
14 Callable,
15 Iterable as TypingIterable,
16 List,
17 Optional,
18 Set,
19 Type,
20 Union,
21 cast,
22 )
23
24 from .abc import AbstractAccessLogger
25 from .helpers import AppKey as AppKey
26 from .log import access_logger
27 from .typedefs import PathLike
28 from .web_app import Application as Application, CleanupError as CleanupError
29 from .web_exceptions import (
30 HTTPAccepted as HTTPAccepted,
31 HTTPBadGateway as HTTPBadGateway,
32 HTTPBadRequest as HTTPBadRequest,
33 HTTPClientError as HTTPClientError,
34 HTTPConflict as HTTPConflict,
35 HTTPCreated as HTTPCreated,
36 HTTPError as HTTPError,
37 HTTPException as HTTPException,
38 HTTPExpectationFailed as HTTPExpectationFailed,
39 HTTPFailedDependency as HTTPFailedDependency,
40 HTTPForbidden as HTTPForbidden,
41 HTTPFound as HTTPFound,
42 HTTPGatewayTimeout as HTTPGatewayTimeout,
43 HTTPGone as HTTPGone,
44 HTTPInsufficientStorage as HTTPInsufficientStorage,
45 HTTPInternalServerError as HTTPInternalServerError,
46 HTTPLengthRequired as HTTPLengthRequired,
47 HTTPMethodNotAllowed as HTTPMethodNotAllowed,
48 HTTPMisdirectedRequest as HTTPMisdirectedRequest,
49 HTTPMove as HTTPMove,
50 HTTPMovedPermanently as HTTPMovedPermanently,
51 HTTPMultipleChoices as HTTPMultipleChoices,
52 HTTPNetworkAuthenticationRequired as HTTPNetworkAuthenticationRequired,
53 HTTPNoContent as HTTPNoContent,
54 HTTPNonAuthoritativeInformation as HTTPNonAuthoritativeInformation,
55 HTTPNotAcceptable as HTTPNotAcceptable,
56 HTTPNotExtended as HTTPNotExtended,
57 HTTPNotFound as HTTPNotFound,
58 HTTPNotImplemented as HTTPNotImplemented,
59 HTTPNotModified as HTTPNotModified,
60 HTTPOk as HTTPOk,
61 HTTPPartialContent as HTTPPartialContent,
62 HTTPPaymentRequired as HTTPPaymentRequired,
63 HTTPPermanentRedirect as HTTPPermanentRedirect,
64 HTTPPreconditionFailed as HTTPPreconditionFailed,
65 HTTPPreconditionRequired as HTTPPreconditionRequired,
66 HTTPProxyAuthenticationRequired as HTTPProxyAuthenticationRequired,
67 HTTPRedirection as HTTPRedirection,
68 HTTPRequestEntityTooLarge as HTTPRequestEntityTooLarge,
69 HTTPRequestHeaderFieldsTooLarge as HTTPRequestHeaderFieldsTooLarge,
70 HTTPRequestRangeNotSatisfiable as HTTPRequestRangeNotSatisfiable,
71 HTTPRequestTimeout as HTTPRequestTimeout,
72 HTTPRequestURITooLong as HTTPRequestURITooLong,
73 HTTPResetContent as HTTPResetContent,
74 HTTPSeeOther as HTTPSeeOther,
75 HTTPServerError as HTTPServerError,
76 HTTPServiceUnavailable as HTTPServiceUnavailable,
77 HTTPSuccessful as HTTPSuccessful,
78 HTTPTemporaryRedirect as HTTPTemporaryRedirect,
79 HTTPTooManyRequests as HTTPTooManyRequests,
80 HTTPUnauthorized as HTTPUnauthorized,
81 HTTPUnavailableForLegalReasons as HTTPUnavailableForLegalReasons,
82 HTTPUnprocessableEntity as HTTPUnprocessableEntity,
83 HTTPUnsupportedMediaType as HTTPUnsupportedMediaType,
84 HTTPUpgradeRequired as HTTPUpgradeRequired,
85 HTTPUseProxy as HTTPUseProxy,
86 HTTPVariantAlsoNegotiates as HTTPVariantAlsoNegotiates,
87 HTTPVersionNotSupported as HTTPVersionNotSupported,
88 NotAppKeyWarning as NotAppKeyWarning,
89 )
90 from .web_fileresponse import FileResponse as FileResponse
91 from .web_log import AccessLogger
92 from .web_middlewares import (
93 middleware as middleware,
94 normalize_path_middleware as normalize_path_middleware,
95 )
96 from .web_protocol import (
97 PayloadAccessError as PayloadAccessError,
98 RequestHandler as RequestHandler,
99 RequestPayloadError as RequestPayloadError,
100 )
101 from .web_request import (
102 BaseRequest as BaseRequest,
103 FileField as FileField,
104 Request as Request,
105 )
106 from .web_response import (
107 ContentCoding as ContentCoding,
108 Response as Response,
109 StreamResponse as StreamResponse,
110 json_response as json_response,
111 )
112 from .web_routedef import (
113 AbstractRouteDef as AbstractRouteDef,
114 RouteDef as RouteDef,
115 RouteTableDef as RouteTableDef,
116 StaticDef as StaticDef,
117 delete as delete,
118 get as get,
119 head as head,
120 options as options,
121 patch as patch,
122 post as post,
123 put as put,
124 route as route,
125 static as static,
126 view as view,
127 )
128 from .web_runner import (
129 AppRunner as AppRunner,
130 BaseRunner as BaseRunner,
131 BaseSite as BaseSite,
132 GracefulExit as GracefulExit,
133 NamedPipeSite as NamedPipeSite,
134 ServerRunner as ServerRunner,
135 SockSite as SockSite,
136 TCPSite as TCPSite,
137 UnixSite as UnixSite,
138 )
139 from .web_server import Server as Server
140 from .web_urldispatcher import (
141 AbstractResource as AbstractResource,
142 AbstractRoute as AbstractRoute,
143 DynamicResource as DynamicResource,
144 PlainResource as PlainResource,
145 PrefixedSubAppResource as PrefixedSubAppResource,
146 Resource as Resource,
147 ResourceRoute as ResourceRoute,
148 StaticResource as StaticResource,
149 UrlDispatcher as UrlDispatcher,
150 UrlMappingMatchInfo as UrlMappingMatchInfo,
151 View as View,
152 )
153 from .web_ws import (
154 WebSocketReady as WebSocketReady,
155 WebSocketResponse as WebSocketResponse,
156 WSMsgType as WSMsgType,
157 )
158
159 __all__ = (
160 # web_app
161 "AppKey",
162 "Application",
163 "CleanupError",
164 # web_exceptions
165 "NotAppKeyWarning",
166 "HTTPAccepted",
167 "HTTPBadGateway",
168 "HTTPBadRequest",
169 "HTTPClientError",
170 "HTTPConflict",
171 "HTTPCreated",
172 "HTTPError",
173 "HTTPException",
174 "HTTPExpectationFailed",
175 "HTTPFailedDependency",
176 "HTTPForbidden",
177 "HTTPFound",
178 "HTTPGatewayTimeout",
179 "HTTPGone",
180 "HTTPInsufficientStorage",
181 "HTTPInternalServerError",
182 "HTTPLengthRequired",
183 "HTTPMethodNotAllowed",
184 "HTTPMisdirectedRequest",
185 "HTTPMove",
186 "HTTPMovedPermanently",
187 "HTTPMultipleChoices",
188 "HTTPNetworkAuthenticationRequired",
189 "HTTPNoContent",
190 "HTTPNonAuthoritativeInformation",
191 "HTTPNotAcceptable",
192 "HTTPNotExtended",
193 "HTTPNotFound",
194 "HTTPNotImplemented",
195 "HTTPNotModified",
196 "HTTPOk",
197 "HTTPPartialContent",
198 "HTTPPaymentRequired",
199 "HTTPPermanentRedirect",
200 "HTTPPreconditionFailed",
201 "HTTPPreconditionRequired",
202 "HTTPProxyAuthenticationRequired",
203 "HTTPRedirection",
204 "HTTPRequestEntityTooLarge",
205 "HTTPRequestHeaderFieldsTooLarge",
206 "HTTPRequestRangeNotSatisfiable",
207 "HTTPRequestTimeout",
208 "HTTPRequestURITooLong",
209 "HTTPResetContent",
210 "HTTPSeeOther",
211 "HTTPServerError",
212 "HTTPServiceUnavailable",
213 "HTTPSuccessful",
214 "HTTPTemporaryRedirect",
215 "HTTPTooManyRequests",
216 "HTTPUnauthorized",
217 "HTTPUnavailableForLegalReasons",
218 "HTTPUnprocessableEntity",
219 "HTTPUnsupportedMediaType",
220 "HTTPUpgradeRequired",
221 "HTTPUseProxy",
222 "HTTPVariantAlsoNegotiates",
223 "HTTPVersionNotSupported",
224 # web_fileresponse
225 "FileResponse",
226 # web_middlewares
227 "middleware",
228 "normalize_path_middleware",
229 # web_protocol
230 "PayloadAccessError",
231 "RequestHandler",
232 "RequestPayloadError",
233 # web_request
234 "BaseRequest",
235 "FileField",
236 "Request",
237 # web_response
238 "ContentCoding",
239 "Response",
240 "StreamResponse",
241 "json_response",
242 # web_routedef
243 "AbstractRouteDef",
244 "RouteDef",
245 "RouteTableDef",
246 "StaticDef",
247 "delete",
248 "get",
249 "head",
250 "options",
251 "patch",
252 "post",
253 "put",
254 "route",
255 "static",
256 "view",
257 # web_runner
258 "AppRunner",
259 "BaseRunner",
260 "BaseSite",
261 "GracefulExit",
262 "ServerRunner",
263 "SockSite",
264 "TCPSite",
265 "UnixSite",
266 "NamedPipeSite",
267 # web_server
268 "Server",
269 # web_urldispatcher
270 "AbstractResource",
271 "AbstractRoute",
272 "DynamicResource",
273 "PlainResource",
274 "PrefixedSubAppResource",
275 "Resource",
276 "ResourceRoute",
277 "StaticResource",
278 "UrlDispatcher",
279 "UrlMappingMatchInfo",
280 "View",
281 # web_ws
282 "WebSocketReady",
283 "WebSocketResponse",
284 "WSMsgType",
285 # web
286 "run_app",
287 )
288
289
290 try:
291 from ssl import SSLContext
292 except ImportError: # pragma: no cover
293 SSLContext = Any # type: ignore[misc,assignment]
294
295 # Only display warning when using -Wdefault, -We, -X dev or similar.
296 warnings.filterwarnings("ignore", category=NotAppKeyWarning, append=True)
297
298 HostSequence = TypingIterable[str]
299
300
301 async def _run_app(
302 app: Union[Application, Awaitable[Application]],
303 *,
304 host: Optional[Union[str, HostSequence]] = None,
305 port: Optional[int] = None,
306 path: Union[PathLike, TypingIterable[PathLike], None] = None,
307 sock: Optional[Union[socket.socket, TypingIterable[socket.socket]]] = None,
308 shutdown_timeout: float = 60.0,
309 keepalive_timeout: float = 75.0,
310 ssl_context: Optional[SSLContext] = None,
311 print: Optional[Callable[..., None]] = print,
312 backlog: int = 128,
313 access_log_class: Type[AbstractAccessLogger] = AccessLogger,
314 access_log_format: str = AccessLogger.LOG_FORMAT,
315 access_log: Optional[logging.Logger] = access_logger,
316 handle_signals: bool = True,
317 reuse_address: Optional[bool] = None,
318 reuse_port: Optional[bool] = None,
319 handler_cancellation: bool = False,
320 ) -> None:
321 # An internal function to actually do all dirty job for application running
322 if asyncio.iscoroutine(app):
323 app = await app
324
325 app = cast(Application, app)
326
327 runner = AppRunner(
328 app,
329 handle_signals=handle_signals,
330 access_log_class=access_log_class,
331 access_log_format=access_log_format,
332 access_log=access_log,
333 keepalive_timeout=keepalive_timeout,
334 shutdown_timeout=shutdown_timeout,
335 handler_cancellation=handler_cancellation,
336 )
337
338 await runner.setup()
339
340 sites: List[BaseSite] = []
341
342 try:
343 if host is not None:
344 if isinstance(host, (str, bytes, bytearray, memoryview)):
345 sites.append(
346 TCPSite(
347 runner,
348 host,
349 port,
350 ssl_context=ssl_context,
351 backlog=backlog,
352 reuse_address=reuse_address,
353 reuse_port=reuse_port,
354 )
355 )
356 else:
357 for h in host:
358 sites.append(
359 TCPSite(
360 runner,
361 h,
362 port,
363 ssl_context=ssl_context,
364 backlog=backlog,
365 reuse_address=reuse_address,
366 reuse_port=reuse_port,
367 )
368 )
369 elif path is None and sock is None or port is not None:
370 sites.append(
371 TCPSite(
372 runner,
373 port=port,
374 ssl_context=ssl_context,
375 backlog=backlog,
376 reuse_address=reuse_address,
377 reuse_port=reuse_port,
378 )
379 )
380
381 if path is not None:
382 if isinstance(path, (str, os.PathLike)):
383 sites.append(
384 UnixSite(
385 runner,
386 path,
387 ssl_context=ssl_context,
388 backlog=backlog,
389 )
390 )
391 else:
392 for p in path:
393 sites.append(
394 UnixSite(
395 runner,
396 p,
397 ssl_context=ssl_context,
398 backlog=backlog,
399 )
400 )
401
402 if sock is not None:
403 if not isinstance(sock, Iterable):
404 sites.append(
405 SockSite(
406 runner,
407 sock,
408 ssl_context=ssl_context,
409 backlog=backlog,
410 )
411 )
412 else:
413 for s in sock:
414 sites.append(
415 SockSite(
416 runner,
417 s,
418 ssl_context=ssl_context,
419 backlog=backlog,
420 )
421 )
422 for site in sites:
423 await site.start()
424
425 if print: # pragma: no branch
426 names = sorted(str(s.name) for s in runner.sites)
427 print(
428 "======== Running on {} ========\n"
429 "(Press CTRL+C to quit)".format(", ".join(names))
430 )
431
432 # sleep forever by 1 hour intervals,
433 while True:
434 await asyncio.sleep(3600)
435 finally:
436 await runner.cleanup()
437
438
439 def _cancel_tasks(
440 to_cancel: Set["asyncio.Task[Any]"], loop: asyncio.AbstractEventLoop
441 ) -> None:
442 if not to_cancel:
443 return
444
445 for task in to_cancel:
446 task.cancel()
447
448 loop.run_until_complete(asyncio.gather(*to_cancel, return_exceptions=True))
449
450 for task in to_cancel:
451 if task.cancelled():
452 continue
453 if task.exception() is not None:
454 loop.call_exception_handler(
455 {
456 "message": "unhandled exception during asyncio.run() shutdown",
457 "exception": task.exception(),
458 "task": task,
459 }
460 )
461
462
463 def run_app(
464 app: Union[Application, Awaitable[Application]],
465 *,
466 host: Optional[Union[str, HostSequence]] = None,
467 port: Optional[int] = None,
468 path: Union[PathLike, TypingIterable[PathLike], None] = None,
469 sock: Optional[Union[socket.socket, TypingIterable[socket.socket]]] = None,
470 shutdown_timeout: float = 60.0,
471 keepalive_timeout: float = 75.0,
472 ssl_context: Optional[SSLContext] = None,
473 print: Optional[Callable[..., None]] = print,
474 backlog: int = 128,
475 access_log_class: Type[AbstractAccessLogger] = AccessLogger,
476 access_log_format: str = AccessLogger.LOG_FORMAT,
477 access_log: Optional[logging.Logger] = access_logger,
478 handle_signals: bool = True,
479 reuse_address: Optional[bool] = None,
480 reuse_port: Optional[bool] = None,
481 handler_cancellation: bool = False,
482 loop: Optional[asyncio.AbstractEventLoop] = None,
483 ) -> None:
484 """Run an app locally"""
485 if loop is None:
486 loop = asyncio.new_event_loop()
487
488 # Configure if and only if in debugging mode and using the default logger
489 if loop.get_debug() and access_log and access_log.name == "aiohttp.access":
490 if access_log.level == logging.NOTSET:
491 access_log.setLevel(logging.DEBUG)
492 if not access_log.hasHandlers():
493 access_log.addHandler(logging.StreamHandler())
494
495 main_task = loop.create_task(
496 _run_app(
497 app,
498 host=host,
499 port=port,
500 path=path,
501 sock=sock,
502 shutdown_timeout=shutdown_timeout,
503 keepalive_timeout=keepalive_timeout,
504 ssl_context=ssl_context,
505 print=print,
506 backlog=backlog,
507 access_log_class=access_log_class,
508 access_log_format=access_log_format,
509 access_log=access_log,
510 handle_signals=handle_signals,
511 reuse_address=reuse_address,
512 reuse_port=reuse_port,
513 handler_cancellation=handler_cancellation,
514 )
515 )
516
517 try:
518 asyncio.set_event_loop(loop)
519 loop.run_until_complete(main_task)
520 except (GracefulExit, KeyboardInterrupt): # pragma: no cover
521 pass
522 finally:
523 try:
524 main_task.cancel()
525 with suppress(asyncio.CancelledError):
526 loop.run_until_complete(main_task)
527 finally:
528 _cancel_tasks(asyncio.all_tasks(loop), loop)
529 loop.run_until_complete(loop.shutdown_asyncgens())
530 loop.close()
531
532
533 def main(argv: List[str]) -> None:
534 arg_parser = ArgumentParser(
535 description="aiohttp.web Application server", prog="aiohttp.web"
536 )
537 arg_parser.add_argument(
538 "entry_func",
539 help=(
540 "Callable returning the `aiohttp.web.Application` instance to "
541 "run. Should be specified in the 'module:function' syntax."
542 ),
543 metavar="entry-func",
544 )
545 arg_parser.add_argument(
546 "-H",
547 "--hostname",
548 help="TCP/IP hostname to serve on (default: %(default)r)",
549 default="localhost",
550 )
551 arg_parser.add_argument(
552 "-P",
553 "--port",
554 help="TCP/IP port to serve on (default: %(default)r)",
555 type=int,
556 default="8080",
557 )
558 arg_parser.add_argument(
559 "-U",
560 "--path",
561 help="Unix file system path to serve on. Specifying a path will cause "
562 "hostname and port arguments to be ignored.",
563 )
564 args, extra_argv = arg_parser.parse_known_args(argv)
565
566 # Import logic
567 mod_str, _, func_str = args.entry_func.partition(":")
568 if not func_str or not mod_str:
569 arg_parser.error("'entry-func' not in 'module:function' syntax")
570 if mod_str.startswith("."):
571 arg_parser.error("relative module names not supported")
572 try:
573 module = import_module(mod_str)
574 except ImportError as ex:
575 arg_parser.error(f"unable to import {mod_str}: {ex}")
576 try:
577 func = getattr(module, func_str)
578 except AttributeError:
579 arg_parser.error(f"module {mod_str!r} has no attribute {func_str!r}")
580
581 # Compatibility logic
582 if args.path is not None and not hasattr(socket, "AF_UNIX"):
583 arg_parser.error(
584 "file system paths not supported by your operating" " environment"
585 )
586
587 logging.basicConfig(level=logging.DEBUG)
588
589 app = func(extra_argv)
590 run_app(app, host=args.hostname, port=args.port, path=args.path)
591 arg_parser.exit(message="Stopped\n")
592
593
594 if __name__ == "__main__": # pragma: no branch
595 main(sys.argv[1:]) # pragma: no cover