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