Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- janus/lib/python3.10/asyncio/__init__.py +43 -0
- janus/lib/python3.10/asyncio/__main__.py +127 -0
- janus/lib/python3.10/asyncio/base_events.py +1934 -0
- janus/lib/python3.10/asyncio/base_tasks.py +85 -0
- janus/lib/python3.10/asyncio/coroutines.py +269 -0
- janus/lib/python3.10/asyncio/events.py +819 -0
- janus/lib/python3.10/asyncio/exceptions.py +58 -0
- janus/lib/python3.10/asyncio/format_helpers.py +76 -0
- janus/lib/python3.10/asyncio/futures.py +426 -0
- janus/lib/python3.10/asyncio/locks.py +438 -0
- janus/lib/python3.10/asyncio/mixins.py +31 -0
- janus/lib/python3.10/asyncio/protocols.py +216 -0
- janus/lib/python3.10/asyncio/selector_events.py +1105 -0
- janus/lib/python3.10/asyncio/subprocess.py +223 -0
- janus/lib/python3.10/asyncio/tasks.py +946 -0
- janus/lib/python3.10/asyncio/threads.py +25 -0
- janus/lib/python3.10/asyncio/windows_events.py +924 -0
- janus/lib/python3.10/asyncio/windows_utils.py +173 -0
- janus/lib/python3.10/site-packages/idna-3.10.dist-info/INSTALLER +1 -0
- janus/lib/python3.10/site-packages/idna-3.10.dist-info/LICENSE.md +31 -0
- janus/lib/python3.10/site-packages/idna-3.10.dist-info/METADATA +250 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/__init__.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/_identifier.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/async_utils.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/compiler.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/constants.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/debug.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/environment.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/ext.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/filters.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/idtracking.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/lexer.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/loaders.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/meta.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/nativetypes.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/nodes.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/optimizer.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/parser.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/runtime.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/sandbox.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/tests.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/utils.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/__pycache__/visitor.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/jinja2/async_utils.py +99 -0
- janus/lib/python3.10/site-packages/jinja2/filters.py +1878 -0
- janus/lib/python3.10/site-packages/jinja2/loaders.py +693 -0
- janus/lib/python3.10/site-packages/jinja2/sandbox.py +436 -0
- janus/lib/python3.10/site-packages/networkx-3.4.2.dist-info/REQUESTED +0 -0
- janus/lib/python3.10/site-packages/networkx-3.4.2.dist-info/top_level.txt +1 -0
.gitattributes
CHANGED
|
@@ -461,3 +461,4 @@ evalkit_cambrian/lib/python3.10/site-packages/cv2/qt/fonts/DejaVuSansCondensed-O
|
|
| 461 |
janus/lib/python3.10/site-packages/pip/_vendor/pkg_resources/__pycache__/__init__.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 462 |
janus/lib/python3.10/site-packages/regex/__pycache__/test_regex.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 463 |
janus/lib/python3.10/site-packages/numpy/ma/__pycache__/core.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 461 |
janus/lib/python3.10/site-packages/pip/_vendor/pkg_resources/__pycache__/__init__.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 462 |
janus/lib/python3.10/site-packages/regex/__pycache__/test_regex.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 463 |
janus/lib/python3.10/site-packages/numpy/ma/__pycache__/core.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 464 |
+
janus/lib/python3.10/site-packages/numpy/linalg/__pycache__/_linalg.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
janus/lib/python3.10/asyncio/__init__.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The asyncio package, tracking PEP 3156."""
|
| 2 |
+
|
| 3 |
+
# flake8: noqa
|
| 4 |
+
|
| 5 |
+
import sys
|
| 6 |
+
|
| 7 |
+
# This relies on each of the submodules having an __all__ variable.
|
| 8 |
+
from .base_events import *
|
| 9 |
+
from .coroutines import *
|
| 10 |
+
from .events import *
|
| 11 |
+
from .exceptions import *
|
| 12 |
+
from .futures import *
|
| 13 |
+
from .locks import *
|
| 14 |
+
from .protocols import *
|
| 15 |
+
from .runners import *
|
| 16 |
+
from .queues import *
|
| 17 |
+
from .streams import *
|
| 18 |
+
from .subprocess import *
|
| 19 |
+
from .tasks import *
|
| 20 |
+
from .threads import *
|
| 21 |
+
from .transports import *
|
| 22 |
+
|
| 23 |
+
__all__ = (base_events.__all__ +
|
| 24 |
+
coroutines.__all__ +
|
| 25 |
+
events.__all__ +
|
| 26 |
+
exceptions.__all__ +
|
| 27 |
+
futures.__all__ +
|
| 28 |
+
locks.__all__ +
|
| 29 |
+
protocols.__all__ +
|
| 30 |
+
runners.__all__ +
|
| 31 |
+
queues.__all__ +
|
| 32 |
+
streams.__all__ +
|
| 33 |
+
subprocess.__all__ +
|
| 34 |
+
tasks.__all__ +
|
| 35 |
+
threads.__all__ +
|
| 36 |
+
transports.__all__)
|
| 37 |
+
|
| 38 |
+
if sys.platform == 'win32': # pragma: no cover
|
| 39 |
+
from .windows_events import *
|
| 40 |
+
__all__ += windows_events.__all__
|
| 41 |
+
else:
|
| 42 |
+
from .unix_events import * # pragma: no cover
|
| 43 |
+
__all__ += unix_events.__all__
|
janus/lib/python3.10/asyncio/__main__.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ast
|
| 2 |
+
import asyncio
|
| 3 |
+
import code
|
| 4 |
+
import concurrent.futures
|
| 5 |
+
import inspect
|
| 6 |
+
import sys
|
| 7 |
+
import threading
|
| 8 |
+
import types
|
| 9 |
+
import warnings
|
| 10 |
+
|
| 11 |
+
from . import futures
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class AsyncIOInteractiveConsole(code.InteractiveConsole):
|
| 15 |
+
|
| 16 |
+
def __init__(self, locals, loop):
|
| 17 |
+
super().__init__(locals)
|
| 18 |
+
self.compile.compiler.flags |= ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
|
| 19 |
+
|
| 20 |
+
self.loop = loop
|
| 21 |
+
|
| 22 |
+
def runcode(self, code):
|
| 23 |
+
future = concurrent.futures.Future()
|
| 24 |
+
|
| 25 |
+
def callback():
|
| 26 |
+
global repl_future
|
| 27 |
+
global repl_future_interrupted
|
| 28 |
+
|
| 29 |
+
repl_future = None
|
| 30 |
+
repl_future_interrupted = False
|
| 31 |
+
|
| 32 |
+
func = types.FunctionType(code, self.locals)
|
| 33 |
+
try:
|
| 34 |
+
coro = func()
|
| 35 |
+
except SystemExit:
|
| 36 |
+
raise
|
| 37 |
+
except KeyboardInterrupt as ex:
|
| 38 |
+
repl_future_interrupted = True
|
| 39 |
+
future.set_exception(ex)
|
| 40 |
+
return
|
| 41 |
+
except BaseException as ex:
|
| 42 |
+
future.set_exception(ex)
|
| 43 |
+
return
|
| 44 |
+
|
| 45 |
+
if not inspect.iscoroutine(coro):
|
| 46 |
+
future.set_result(coro)
|
| 47 |
+
return
|
| 48 |
+
|
| 49 |
+
try:
|
| 50 |
+
repl_future = self.loop.create_task(coro)
|
| 51 |
+
futures._chain_future(repl_future, future)
|
| 52 |
+
except BaseException as exc:
|
| 53 |
+
future.set_exception(exc)
|
| 54 |
+
|
| 55 |
+
loop.call_soon_threadsafe(callback)
|
| 56 |
+
|
| 57 |
+
try:
|
| 58 |
+
return future.result()
|
| 59 |
+
except SystemExit:
|
| 60 |
+
raise
|
| 61 |
+
except BaseException:
|
| 62 |
+
if repl_future_interrupted:
|
| 63 |
+
self.write("\nKeyboardInterrupt\n")
|
| 64 |
+
else:
|
| 65 |
+
self.showtraceback()
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class REPLThread(threading.Thread):
|
| 69 |
+
|
| 70 |
+
def run(self):
|
| 71 |
+
try:
|
| 72 |
+
banner = (
|
| 73 |
+
f'asyncio REPL {sys.version} on {sys.platform}\n'
|
| 74 |
+
f'Use "await" directly instead of "asyncio.run()".\n'
|
| 75 |
+
f'Type "help", "copyright", "credits" or "license" '
|
| 76 |
+
f'for more information.\n'
|
| 77 |
+
f'{getattr(sys, "ps1", ">>> ")}import asyncio'
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
console.interact(
|
| 81 |
+
banner=banner,
|
| 82 |
+
exitmsg='exiting asyncio REPL...')
|
| 83 |
+
finally:
|
| 84 |
+
warnings.filterwarnings(
|
| 85 |
+
'ignore',
|
| 86 |
+
message=r'^coroutine .* was never awaited$',
|
| 87 |
+
category=RuntimeWarning)
|
| 88 |
+
|
| 89 |
+
loop.call_soon_threadsafe(loop.stop)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
if __name__ == '__main__':
|
| 93 |
+
sys.audit("cpython.run_stdin")
|
| 94 |
+
|
| 95 |
+
loop = asyncio.new_event_loop()
|
| 96 |
+
asyncio.set_event_loop(loop)
|
| 97 |
+
|
| 98 |
+
repl_locals = {'asyncio': asyncio}
|
| 99 |
+
for key in {'__name__', '__package__',
|
| 100 |
+
'__loader__', '__spec__',
|
| 101 |
+
'__builtins__', '__file__'}:
|
| 102 |
+
repl_locals[key] = locals()[key]
|
| 103 |
+
|
| 104 |
+
console = AsyncIOInteractiveConsole(repl_locals, loop)
|
| 105 |
+
|
| 106 |
+
repl_future = None
|
| 107 |
+
repl_future_interrupted = False
|
| 108 |
+
|
| 109 |
+
try:
|
| 110 |
+
import readline # NoQA
|
| 111 |
+
except ImportError:
|
| 112 |
+
pass
|
| 113 |
+
|
| 114 |
+
repl_thread = REPLThread()
|
| 115 |
+
repl_thread.daemon = True
|
| 116 |
+
repl_thread.start()
|
| 117 |
+
|
| 118 |
+
while True:
|
| 119 |
+
try:
|
| 120 |
+
loop.run_forever()
|
| 121 |
+
except KeyboardInterrupt:
|
| 122 |
+
if repl_future and not repl_future.done():
|
| 123 |
+
repl_future.cancel()
|
| 124 |
+
repl_future_interrupted = True
|
| 125 |
+
continue
|
| 126 |
+
else:
|
| 127 |
+
break
|
janus/lib/python3.10/asyncio/base_events.py
ADDED
|
@@ -0,0 +1,1934 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Base implementation of event loop.
|
| 2 |
+
|
| 3 |
+
The event loop can be broken up into a multiplexer (the part
|
| 4 |
+
responsible for notifying us of I/O events) and the event loop proper,
|
| 5 |
+
which wraps a multiplexer with functionality for scheduling callbacks,
|
| 6 |
+
immediately or at a given time in the future.
|
| 7 |
+
|
| 8 |
+
Whenever a public API takes a callback, subsequent positional
|
| 9 |
+
arguments will be passed to the callback if/when it is called. This
|
| 10 |
+
avoids the proliferation of trivial lambdas implementing closures.
|
| 11 |
+
Keyword arguments for the callback are not supported; this is a
|
| 12 |
+
conscious design decision, leaving the door open for keyword arguments
|
| 13 |
+
to modify the meaning of the API call itself.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import collections
|
| 17 |
+
import collections.abc
|
| 18 |
+
import concurrent.futures
|
| 19 |
+
import functools
|
| 20 |
+
import heapq
|
| 21 |
+
import itertools
|
| 22 |
+
import os
|
| 23 |
+
import socket
|
| 24 |
+
import stat
|
| 25 |
+
import subprocess
|
| 26 |
+
import threading
|
| 27 |
+
import time
|
| 28 |
+
import traceback
|
| 29 |
+
import sys
|
| 30 |
+
import warnings
|
| 31 |
+
import weakref
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
import ssl
|
| 35 |
+
except ImportError: # pragma: no cover
|
| 36 |
+
ssl = None
|
| 37 |
+
|
| 38 |
+
from . import constants
|
| 39 |
+
from . import coroutines
|
| 40 |
+
from . import events
|
| 41 |
+
from . import exceptions
|
| 42 |
+
from . import futures
|
| 43 |
+
from . import protocols
|
| 44 |
+
from . import sslproto
|
| 45 |
+
from . import staggered
|
| 46 |
+
from . import tasks
|
| 47 |
+
from . import transports
|
| 48 |
+
from . import trsock
|
| 49 |
+
from .log import logger
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
__all__ = 'BaseEventLoop','Server',
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# Minimum number of _scheduled timer handles before cleanup of
|
| 56 |
+
# cancelled handles is performed.
|
| 57 |
+
_MIN_SCHEDULED_TIMER_HANDLES = 100
|
| 58 |
+
|
| 59 |
+
# Minimum fraction of _scheduled timer handles that are cancelled
|
| 60 |
+
# before cleanup of cancelled handles is performed.
|
| 61 |
+
_MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
_HAS_IPv6 = hasattr(socket, 'AF_INET6')
|
| 65 |
+
|
| 66 |
+
# Maximum timeout passed to select to avoid OS limitations
|
| 67 |
+
MAXIMUM_SELECT_TIMEOUT = 24 * 3600
|
| 68 |
+
|
| 69 |
+
# Used for deprecation and removal of `loop.create_datagram_endpoint()`'s
|
| 70 |
+
# *reuse_address* parameter
|
| 71 |
+
_unset = object()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _format_handle(handle):
|
| 75 |
+
cb = handle._callback
|
| 76 |
+
if isinstance(getattr(cb, '__self__', None), tasks.Task):
|
| 77 |
+
# format the task
|
| 78 |
+
return repr(cb.__self__)
|
| 79 |
+
else:
|
| 80 |
+
return str(handle)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _format_pipe(fd):
|
| 84 |
+
if fd == subprocess.PIPE:
|
| 85 |
+
return '<pipe>'
|
| 86 |
+
elif fd == subprocess.STDOUT:
|
| 87 |
+
return '<stdout>'
|
| 88 |
+
else:
|
| 89 |
+
return repr(fd)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _set_reuseport(sock):
|
| 93 |
+
if not hasattr(socket, 'SO_REUSEPORT'):
|
| 94 |
+
raise ValueError('reuse_port not supported by socket module')
|
| 95 |
+
else:
|
| 96 |
+
try:
|
| 97 |
+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
|
| 98 |
+
except OSError:
|
| 99 |
+
raise ValueError('reuse_port not supported by socket module, '
|
| 100 |
+
'SO_REUSEPORT defined but not implemented.')
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _ipaddr_info(host, port, family, type, proto, flowinfo=0, scopeid=0):
|
| 104 |
+
# Try to skip getaddrinfo if "host" is already an IP. Users might have
|
| 105 |
+
# handled name resolution in their own code and pass in resolved IPs.
|
| 106 |
+
if not hasattr(socket, 'inet_pton'):
|
| 107 |
+
return
|
| 108 |
+
|
| 109 |
+
if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
|
| 110 |
+
host is None:
|
| 111 |
+
return None
|
| 112 |
+
|
| 113 |
+
if type == socket.SOCK_STREAM:
|
| 114 |
+
proto = socket.IPPROTO_TCP
|
| 115 |
+
elif type == socket.SOCK_DGRAM:
|
| 116 |
+
proto = socket.IPPROTO_UDP
|
| 117 |
+
else:
|
| 118 |
+
return None
|
| 119 |
+
|
| 120 |
+
if port is None:
|
| 121 |
+
port = 0
|
| 122 |
+
elif isinstance(port, bytes) and port == b'':
|
| 123 |
+
port = 0
|
| 124 |
+
elif isinstance(port, str) and port == '':
|
| 125 |
+
port = 0
|
| 126 |
+
else:
|
| 127 |
+
# If port's a service name like "http", don't skip getaddrinfo.
|
| 128 |
+
try:
|
| 129 |
+
port = int(port)
|
| 130 |
+
except (TypeError, ValueError):
|
| 131 |
+
return None
|
| 132 |
+
|
| 133 |
+
if family == socket.AF_UNSPEC:
|
| 134 |
+
afs = [socket.AF_INET]
|
| 135 |
+
if _HAS_IPv6:
|
| 136 |
+
afs.append(socket.AF_INET6)
|
| 137 |
+
else:
|
| 138 |
+
afs = [family]
|
| 139 |
+
|
| 140 |
+
if isinstance(host, bytes):
|
| 141 |
+
host = host.decode('idna')
|
| 142 |
+
if '%' in host:
|
| 143 |
+
# Linux's inet_pton doesn't accept an IPv6 zone index after host,
|
| 144 |
+
# like '::1%lo0'.
|
| 145 |
+
return None
|
| 146 |
+
|
| 147 |
+
for af in afs:
|
| 148 |
+
try:
|
| 149 |
+
socket.inet_pton(af, host)
|
| 150 |
+
# The host has already been resolved.
|
| 151 |
+
if _HAS_IPv6 and af == socket.AF_INET6:
|
| 152 |
+
return af, type, proto, '', (host, port, flowinfo, scopeid)
|
| 153 |
+
else:
|
| 154 |
+
return af, type, proto, '', (host, port)
|
| 155 |
+
except OSError:
|
| 156 |
+
pass
|
| 157 |
+
|
| 158 |
+
# "host" is not an IP address.
|
| 159 |
+
return None
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def _interleave_addrinfos(addrinfos, first_address_family_count=1):
|
| 163 |
+
"""Interleave list of addrinfo tuples by family."""
|
| 164 |
+
# Group addresses by family
|
| 165 |
+
addrinfos_by_family = collections.OrderedDict()
|
| 166 |
+
for addr in addrinfos:
|
| 167 |
+
family = addr[0]
|
| 168 |
+
if family not in addrinfos_by_family:
|
| 169 |
+
addrinfos_by_family[family] = []
|
| 170 |
+
addrinfos_by_family[family].append(addr)
|
| 171 |
+
addrinfos_lists = list(addrinfos_by_family.values())
|
| 172 |
+
|
| 173 |
+
reordered = []
|
| 174 |
+
if first_address_family_count > 1:
|
| 175 |
+
reordered.extend(addrinfos_lists[0][:first_address_family_count - 1])
|
| 176 |
+
del addrinfos_lists[0][:first_address_family_count - 1]
|
| 177 |
+
reordered.extend(
|
| 178 |
+
a for a in itertools.chain.from_iterable(
|
| 179 |
+
itertools.zip_longest(*addrinfos_lists)
|
| 180 |
+
) if a is not None)
|
| 181 |
+
return reordered
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _run_until_complete_cb(fut):
|
| 185 |
+
if not fut.cancelled():
|
| 186 |
+
exc = fut.exception()
|
| 187 |
+
if isinstance(exc, (SystemExit, KeyboardInterrupt)):
|
| 188 |
+
# Issue #22429: run_forever() already finished, no need to
|
| 189 |
+
# stop it.
|
| 190 |
+
return
|
| 191 |
+
futures._get_loop(fut).stop()
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
if hasattr(socket, 'TCP_NODELAY'):
|
| 195 |
+
def _set_nodelay(sock):
|
| 196 |
+
if (sock.family in {socket.AF_INET, socket.AF_INET6} and
|
| 197 |
+
sock.type == socket.SOCK_STREAM and
|
| 198 |
+
sock.proto == socket.IPPROTO_TCP):
|
| 199 |
+
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
| 200 |
+
else:
|
| 201 |
+
def _set_nodelay(sock):
|
| 202 |
+
pass
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def _check_ssl_socket(sock):
|
| 206 |
+
if ssl is not None and isinstance(sock, ssl.SSLSocket):
|
| 207 |
+
raise TypeError("Socket cannot be of type SSLSocket")
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class _SendfileFallbackProtocol(protocols.Protocol):
|
| 211 |
+
def __init__(self, transp):
|
| 212 |
+
if not isinstance(transp, transports._FlowControlMixin):
|
| 213 |
+
raise TypeError("transport should be _FlowControlMixin instance")
|
| 214 |
+
self._transport = transp
|
| 215 |
+
self._proto = transp.get_protocol()
|
| 216 |
+
self._should_resume_reading = transp.is_reading()
|
| 217 |
+
self._should_resume_writing = transp._protocol_paused
|
| 218 |
+
transp.pause_reading()
|
| 219 |
+
transp.set_protocol(self)
|
| 220 |
+
if self._should_resume_writing:
|
| 221 |
+
self._write_ready_fut = self._transport._loop.create_future()
|
| 222 |
+
else:
|
| 223 |
+
self._write_ready_fut = None
|
| 224 |
+
|
| 225 |
+
async def drain(self):
|
| 226 |
+
if self._transport.is_closing():
|
| 227 |
+
raise ConnectionError("Connection closed by peer")
|
| 228 |
+
fut = self._write_ready_fut
|
| 229 |
+
if fut is None:
|
| 230 |
+
return
|
| 231 |
+
await fut
|
| 232 |
+
|
| 233 |
+
def connection_made(self, transport):
|
| 234 |
+
raise RuntimeError("Invalid state: "
|
| 235 |
+
"connection should have been established already.")
|
| 236 |
+
|
| 237 |
+
def connection_lost(self, exc):
|
| 238 |
+
if self._write_ready_fut is not None:
|
| 239 |
+
# Never happens if peer disconnects after sending the whole content
|
| 240 |
+
# Thus disconnection is always an exception from user perspective
|
| 241 |
+
if exc is None:
|
| 242 |
+
self._write_ready_fut.set_exception(
|
| 243 |
+
ConnectionError("Connection is closed by peer"))
|
| 244 |
+
else:
|
| 245 |
+
self._write_ready_fut.set_exception(exc)
|
| 246 |
+
self._proto.connection_lost(exc)
|
| 247 |
+
|
| 248 |
+
def pause_writing(self):
|
| 249 |
+
if self._write_ready_fut is not None:
|
| 250 |
+
return
|
| 251 |
+
self._write_ready_fut = self._transport._loop.create_future()
|
| 252 |
+
|
| 253 |
+
def resume_writing(self):
|
| 254 |
+
if self._write_ready_fut is None:
|
| 255 |
+
return
|
| 256 |
+
self._write_ready_fut.set_result(False)
|
| 257 |
+
self._write_ready_fut = None
|
| 258 |
+
|
| 259 |
+
def data_received(self, data):
|
| 260 |
+
raise RuntimeError("Invalid state: reading should be paused")
|
| 261 |
+
|
| 262 |
+
def eof_received(self):
|
| 263 |
+
raise RuntimeError("Invalid state: reading should be paused")
|
| 264 |
+
|
| 265 |
+
async def restore(self):
|
| 266 |
+
self._transport.set_protocol(self._proto)
|
| 267 |
+
if self._should_resume_reading:
|
| 268 |
+
self._transport.resume_reading()
|
| 269 |
+
if self._write_ready_fut is not None:
|
| 270 |
+
# Cancel the future.
|
| 271 |
+
# Basically it has no effect because protocol is switched back,
|
| 272 |
+
# no code should wait for it anymore.
|
| 273 |
+
self._write_ready_fut.cancel()
|
| 274 |
+
if self._should_resume_writing:
|
| 275 |
+
self._proto.resume_writing()
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
class Server(events.AbstractServer):
|
| 279 |
+
|
| 280 |
+
def __init__(self, loop, sockets, protocol_factory, ssl_context, backlog,
|
| 281 |
+
ssl_handshake_timeout):
|
| 282 |
+
self._loop = loop
|
| 283 |
+
self._sockets = sockets
|
| 284 |
+
self._active_count = 0
|
| 285 |
+
self._waiters = []
|
| 286 |
+
self._protocol_factory = protocol_factory
|
| 287 |
+
self._backlog = backlog
|
| 288 |
+
self._ssl_context = ssl_context
|
| 289 |
+
self._ssl_handshake_timeout = ssl_handshake_timeout
|
| 290 |
+
self._serving = False
|
| 291 |
+
self._serving_forever_fut = None
|
| 292 |
+
|
| 293 |
+
def __repr__(self):
|
| 294 |
+
return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
|
| 295 |
+
|
| 296 |
+
def _attach(self):
|
| 297 |
+
assert self._sockets is not None
|
| 298 |
+
self._active_count += 1
|
| 299 |
+
|
| 300 |
+
def _detach(self):
|
| 301 |
+
assert self._active_count > 0
|
| 302 |
+
self._active_count -= 1
|
| 303 |
+
if self._active_count == 0 and self._sockets is None:
|
| 304 |
+
self._wakeup()
|
| 305 |
+
|
| 306 |
+
def _wakeup(self):
|
| 307 |
+
waiters = self._waiters
|
| 308 |
+
self._waiters = None
|
| 309 |
+
for waiter in waiters:
|
| 310 |
+
if not waiter.done():
|
| 311 |
+
waiter.set_result(waiter)
|
| 312 |
+
|
| 313 |
+
def _start_serving(self):
|
| 314 |
+
if self._serving:
|
| 315 |
+
return
|
| 316 |
+
self._serving = True
|
| 317 |
+
for sock in self._sockets:
|
| 318 |
+
sock.listen(self._backlog)
|
| 319 |
+
self._loop._start_serving(
|
| 320 |
+
self._protocol_factory, sock, self._ssl_context,
|
| 321 |
+
self, self._backlog, self._ssl_handshake_timeout)
|
| 322 |
+
|
| 323 |
+
def get_loop(self):
|
| 324 |
+
return self._loop
|
| 325 |
+
|
| 326 |
+
def is_serving(self):
|
| 327 |
+
return self._serving
|
| 328 |
+
|
| 329 |
+
@property
|
| 330 |
+
def sockets(self):
|
| 331 |
+
if self._sockets is None:
|
| 332 |
+
return ()
|
| 333 |
+
return tuple(trsock.TransportSocket(s) for s in self._sockets)
|
| 334 |
+
|
| 335 |
+
def close(self):
|
| 336 |
+
sockets = self._sockets
|
| 337 |
+
if sockets is None:
|
| 338 |
+
return
|
| 339 |
+
self._sockets = None
|
| 340 |
+
|
| 341 |
+
for sock in sockets:
|
| 342 |
+
self._loop._stop_serving(sock)
|
| 343 |
+
|
| 344 |
+
self._serving = False
|
| 345 |
+
|
| 346 |
+
if (self._serving_forever_fut is not None and
|
| 347 |
+
not self._serving_forever_fut.done()):
|
| 348 |
+
self._serving_forever_fut.cancel()
|
| 349 |
+
self._serving_forever_fut = None
|
| 350 |
+
|
| 351 |
+
if self._active_count == 0:
|
| 352 |
+
self._wakeup()
|
| 353 |
+
|
| 354 |
+
async def start_serving(self):
|
| 355 |
+
self._start_serving()
|
| 356 |
+
# Skip one loop iteration so that all 'loop.add_reader'
|
| 357 |
+
# go through.
|
| 358 |
+
await tasks.sleep(0)
|
| 359 |
+
|
| 360 |
+
async def serve_forever(self):
|
| 361 |
+
if self._serving_forever_fut is not None:
|
| 362 |
+
raise RuntimeError(
|
| 363 |
+
f'server {self!r} is already being awaited on serve_forever()')
|
| 364 |
+
if self._sockets is None:
|
| 365 |
+
raise RuntimeError(f'server {self!r} is closed')
|
| 366 |
+
|
| 367 |
+
self._start_serving()
|
| 368 |
+
self._serving_forever_fut = self._loop.create_future()
|
| 369 |
+
|
| 370 |
+
try:
|
| 371 |
+
await self._serving_forever_fut
|
| 372 |
+
except exceptions.CancelledError:
|
| 373 |
+
try:
|
| 374 |
+
self.close()
|
| 375 |
+
await self.wait_closed()
|
| 376 |
+
finally:
|
| 377 |
+
raise
|
| 378 |
+
finally:
|
| 379 |
+
self._serving_forever_fut = None
|
| 380 |
+
|
| 381 |
+
async def wait_closed(self):
|
| 382 |
+
if self._sockets is None or self._waiters is None:
|
| 383 |
+
return
|
| 384 |
+
waiter = self._loop.create_future()
|
| 385 |
+
self._waiters.append(waiter)
|
| 386 |
+
await waiter
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
class BaseEventLoop(events.AbstractEventLoop):
|
| 390 |
+
|
| 391 |
+
def __init__(self):
|
| 392 |
+
self._timer_cancelled_count = 0
|
| 393 |
+
self._closed = False
|
| 394 |
+
self._stopping = False
|
| 395 |
+
self._ready = collections.deque()
|
| 396 |
+
self._scheduled = []
|
| 397 |
+
self._default_executor = None
|
| 398 |
+
self._internal_fds = 0
|
| 399 |
+
# Identifier of the thread running the event loop, or None if the
|
| 400 |
+
# event loop is not running
|
| 401 |
+
self._thread_id = None
|
| 402 |
+
self._clock_resolution = time.get_clock_info('monotonic').resolution
|
| 403 |
+
self._exception_handler = None
|
| 404 |
+
self.set_debug(coroutines._is_debug_mode())
|
| 405 |
+
# In debug mode, if the execution of a callback or a step of a task
|
| 406 |
+
# exceed this duration in seconds, the slow callback/task is logged.
|
| 407 |
+
self.slow_callback_duration = 0.1
|
| 408 |
+
self._current_handle = None
|
| 409 |
+
self._task_factory = None
|
| 410 |
+
self._coroutine_origin_tracking_enabled = False
|
| 411 |
+
self._coroutine_origin_tracking_saved_depth = None
|
| 412 |
+
|
| 413 |
+
# A weak set of all asynchronous generators that are
|
| 414 |
+
# being iterated by the loop.
|
| 415 |
+
self._asyncgens = weakref.WeakSet()
|
| 416 |
+
# Set to True when `loop.shutdown_asyncgens` is called.
|
| 417 |
+
self._asyncgens_shutdown_called = False
|
| 418 |
+
# Set to True when `loop.shutdown_default_executor` is called.
|
| 419 |
+
self._executor_shutdown_called = False
|
| 420 |
+
|
| 421 |
+
def __repr__(self):
|
| 422 |
+
return (
|
| 423 |
+
f'<{self.__class__.__name__} running={self.is_running()} '
|
| 424 |
+
f'closed={self.is_closed()} debug={self.get_debug()}>'
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
def create_future(self):
|
| 428 |
+
"""Create a Future object attached to the loop."""
|
| 429 |
+
return futures.Future(loop=self)
|
| 430 |
+
|
| 431 |
+
def create_task(self, coro, *, name=None):
|
| 432 |
+
"""Schedule a coroutine object.
|
| 433 |
+
|
| 434 |
+
Return a task object.
|
| 435 |
+
"""
|
| 436 |
+
self._check_closed()
|
| 437 |
+
if self._task_factory is None:
|
| 438 |
+
task = tasks.Task(coro, loop=self, name=name)
|
| 439 |
+
if task._source_traceback:
|
| 440 |
+
del task._source_traceback[-1]
|
| 441 |
+
else:
|
| 442 |
+
task = self._task_factory(self, coro)
|
| 443 |
+
tasks._set_task_name(task, name)
|
| 444 |
+
|
| 445 |
+
return task
|
| 446 |
+
|
| 447 |
+
def set_task_factory(self, factory):
|
| 448 |
+
"""Set a task factory that will be used by loop.create_task().
|
| 449 |
+
|
| 450 |
+
If factory is None the default task factory will be set.
|
| 451 |
+
|
| 452 |
+
If factory is a callable, it should have a signature matching
|
| 453 |
+
'(loop, coro)', where 'loop' will be a reference to the active
|
| 454 |
+
event loop, 'coro' will be a coroutine object. The callable
|
| 455 |
+
must return a Future.
|
| 456 |
+
"""
|
| 457 |
+
if factory is not None and not callable(factory):
|
| 458 |
+
raise TypeError('task factory must be a callable or None')
|
| 459 |
+
self._task_factory = factory
|
| 460 |
+
|
| 461 |
+
def get_task_factory(self):
|
| 462 |
+
"""Return a task factory, or None if the default one is in use."""
|
| 463 |
+
return self._task_factory
|
| 464 |
+
|
| 465 |
+
def _make_socket_transport(self, sock, protocol, waiter=None, *,
|
| 466 |
+
extra=None, server=None):
|
| 467 |
+
"""Create socket transport."""
|
| 468 |
+
raise NotImplementedError
|
| 469 |
+
|
| 470 |
+
def _make_ssl_transport(
|
| 471 |
+
self, rawsock, protocol, sslcontext, waiter=None,
|
| 472 |
+
*, server_side=False, server_hostname=None,
|
| 473 |
+
extra=None, server=None,
|
| 474 |
+
ssl_handshake_timeout=None,
|
| 475 |
+
call_connection_made=True):
|
| 476 |
+
"""Create SSL transport."""
|
| 477 |
+
raise NotImplementedError
|
| 478 |
+
|
| 479 |
+
def _make_datagram_transport(self, sock, protocol,
|
| 480 |
+
address=None, waiter=None, extra=None):
|
| 481 |
+
"""Create datagram transport."""
|
| 482 |
+
raise NotImplementedError
|
| 483 |
+
|
| 484 |
+
def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
|
| 485 |
+
extra=None):
|
| 486 |
+
"""Create read pipe transport."""
|
| 487 |
+
raise NotImplementedError
|
| 488 |
+
|
| 489 |
+
def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
|
| 490 |
+
extra=None):
|
| 491 |
+
"""Create write pipe transport."""
|
| 492 |
+
raise NotImplementedError
|
| 493 |
+
|
| 494 |
+
async def _make_subprocess_transport(self, protocol, args, shell,
|
| 495 |
+
stdin, stdout, stderr, bufsize,
|
| 496 |
+
extra=None, **kwargs):
|
| 497 |
+
"""Create subprocess transport."""
|
| 498 |
+
raise NotImplementedError
|
| 499 |
+
|
| 500 |
+
def _write_to_self(self):
|
| 501 |
+
"""Write a byte to self-pipe, to wake up the event loop.
|
| 502 |
+
|
| 503 |
+
This may be called from a different thread.
|
| 504 |
+
|
| 505 |
+
The subclass is responsible for implementing the self-pipe.
|
| 506 |
+
"""
|
| 507 |
+
raise NotImplementedError
|
| 508 |
+
|
| 509 |
+
def _process_events(self, event_list):
|
| 510 |
+
"""Process selector events."""
|
| 511 |
+
raise NotImplementedError
|
| 512 |
+
|
| 513 |
+
def _check_closed(self):
|
| 514 |
+
if self._closed:
|
| 515 |
+
raise RuntimeError('Event loop is closed')
|
| 516 |
+
|
| 517 |
+
def _check_default_executor(self):
|
| 518 |
+
if self._executor_shutdown_called:
|
| 519 |
+
raise RuntimeError('Executor shutdown has been called')
|
| 520 |
+
|
| 521 |
+
def _asyncgen_finalizer_hook(self, agen):
|
| 522 |
+
self._asyncgens.discard(agen)
|
| 523 |
+
if not self.is_closed():
|
| 524 |
+
self.call_soon_threadsafe(self.create_task, agen.aclose())
|
| 525 |
+
|
| 526 |
+
def _asyncgen_firstiter_hook(self, agen):
|
| 527 |
+
if self._asyncgens_shutdown_called:
|
| 528 |
+
warnings.warn(
|
| 529 |
+
f"asynchronous generator {agen!r} was scheduled after "
|
| 530 |
+
f"loop.shutdown_asyncgens() call",
|
| 531 |
+
ResourceWarning, source=self)
|
| 532 |
+
|
| 533 |
+
self._asyncgens.add(agen)
|
| 534 |
+
|
| 535 |
+
async def shutdown_asyncgens(self):
|
| 536 |
+
"""Shutdown all active asynchronous generators."""
|
| 537 |
+
self._asyncgens_shutdown_called = True
|
| 538 |
+
|
| 539 |
+
if not len(self._asyncgens):
|
| 540 |
+
# If Python version is <3.6 or we don't have any asynchronous
|
| 541 |
+
# generators alive.
|
| 542 |
+
return
|
| 543 |
+
|
| 544 |
+
closing_agens = list(self._asyncgens)
|
| 545 |
+
self._asyncgens.clear()
|
| 546 |
+
|
| 547 |
+
results = await tasks.gather(
|
| 548 |
+
*[ag.aclose() for ag in closing_agens],
|
| 549 |
+
return_exceptions=True)
|
| 550 |
+
|
| 551 |
+
for result, agen in zip(results, closing_agens):
|
| 552 |
+
if isinstance(result, Exception):
|
| 553 |
+
self.call_exception_handler({
|
| 554 |
+
'message': f'an error occurred during closing of '
|
| 555 |
+
f'asynchronous generator {agen!r}',
|
| 556 |
+
'exception': result,
|
| 557 |
+
'asyncgen': agen
|
| 558 |
+
})
|
| 559 |
+
|
| 560 |
+
async def shutdown_default_executor(self):
|
| 561 |
+
"""Schedule the shutdown of the default executor."""
|
| 562 |
+
self._executor_shutdown_called = True
|
| 563 |
+
if self._default_executor is None:
|
| 564 |
+
return
|
| 565 |
+
future = self.create_future()
|
| 566 |
+
thread = threading.Thread(target=self._do_shutdown, args=(future,))
|
| 567 |
+
thread.start()
|
| 568 |
+
try:
|
| 569 |
+
await future
|
| 570 |
+
finally:
|
| 571 |
+
thread.join()
|
| 572 |
+
|
| 573 |
+
def _do_shutdown(self, future):
|
| 574 |
+
try:
|
| 575 |
+
self._default_executor.shutdown(wait=True)
|
| 576 |
+
if not self.is_closed():
|
| 577 |
+
self.call_soon_threadsafe(future.set_result, None)
|
| 578 |
+
except Exception as ex:
|
| 579 |
+
if not self.is_closed():
|
| 580 |
+
self.call_soon_threadsafe(future.set_exception, ex)
|
| 581 |
+
|
| 582 |
+
def _check_running(self):
|
| 583 |
+
if self.is_running():
|
| 584 |
+
raise RuntimeError('This event loop is already running')
|
| 585 |
+
if events._get_running_loop() is not None:
|
| 586 |
+
raise RuntimeError(
|
| 587 |
+
'Cannot run the event loop while another loop is running')
|
| 588 |
+
|
| 589 |
+
def run_forever(self):
|
| 590 |
+
"""Run until stop() is called."""
|
| 591 |
+
self._check_closed()
|
| 592 |
+
self._check_running()
|
| 593 |
+
self._set_coroutine_origin_tracking(self._debug)
|
| 594 |
+
|
| 595 |
+
old_agen_hooks = sys.get_asyncgen_hooks()
|
| 596 |
+
try:
|
| 597 |
+
self._thread_id = threading.get_ident()
|
| 598 |
+
sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
|
| 599 |
+
finalizer=self._asyncgen_finalizer_hook)
|
| 600 |
+
|
| 601 |
+
events._set_running_loop(self)
|
| 602 |
+
while True:
|
| 603 |
+
self._run_once()
|
| 604 |
+
if self._stopping:
|
| 605 |
+
break
|
| 606 |
+
finally:
|
| 607 |
+
self._stopping = False
|
| 608 |
+
self._thread_id = None
|
| 609 |
+
events._set_running_loop(None)
|
| 610 |
+
self._set_coroutine_origin_tracking(False)
|
| 611 |
+
sys.set_asyncgen_hooks(*old_agen_hooks)
|
| 612 |
+
|
| 613 |
+
def run_until_complete(self, future):
|
| 614 |
+
"""Run until the Future is done.
|
| 615 |
+
|
| 616 |
+
If the argument is a coroutine, it is wrapped in a Task.
|
| 617 |
+
|
| 618 |
+
WARNING: It would be disastrous to call run_until_complete()
|
| 619 |
+
with the same coroutine twice -- it would wrap it in two
|
| 620 |
+
different Tasks and that can't be good.
|
| 621 |
+
|
| 622 |
+
Return the Future's result, or raise its exception.
|
| 623 |
+
"""
|
| 624 |
+
self._check_closed()
|
| 625 |
+
self._check_running()
|
| 626 |
+
|
| 627 |
+
new_task = not futures.isfuture(future)
|
| 628 |
+
future = tasks.ensure_future(future, loop=self)
|
| 629 |
+
if new_task:
|
| 630 |
+
# An exception is raised if the future didn't complete, so there
|
| 631 |
+
# is no need to log the "destroy pending task" message
|
| 632 |
+
future._log_destroy_pending = False
|
| 633 |
+
|
| 634 |
+
future.add_done_callback(_run_until_complete_cb)
|
| 635 |
+
try:
|
| 636 |
+
self.run_forever()
|
| 637 |
+
except:
|
| 638 |
+
if new_task and future.done() and not future.cancelled():
|
| 639 |
+
# The coroutine raised a BaseException. Consume the exception
|
| 640 |
+
# to not log a warning, the caller doesn't have access to the
|
| 641 |
+
# local task.
|
| 642 |
+
future.exception()
|
| 643 |
+
raise
|
| 644 |
+
finally:
|
| 645 |
+
future.remove_done_callback(_run_until_complete_cb)
|
| 646 |
+
if not future.done():
|
| 647 |
+
raise RuntimeError('Event loop stopped before Future completed.')
|
| 648 |
+
|
| 649 |
+
return future.result()
|
| 650 |
+
|
| 651 |
+
def stop(self):
|
| 652 |
+
"""Stop running the event loop.
|
| 653 |
+
|
| 654 |
+
Every callback already scheduled will still run. This simply informs
|
| 655 |
+
run_forever to stop looping after a complete iteration.
|
| 656 |
+
"""
|
| 657 |
+
self._stopping = True
|
| 658 |
+
|
| 659 |
+
def close(self):
|
| 660 |
+
"""Close the event loop.
|
| 661 |
+
|
| 662 |
+
This clears the queues and shuts down the executor,
|
| 663 |
+
but does not wait for the executor to finish.
|
| 664 |
+
|
| 665 |
+
The event loop must not be running.
|
| 666 |
+
"""
|
| 667 |
+
if self.is_running():
|
| 668 |
+
raise RuntimeError("Cannot close a running event loop")
|
| 669 |
+
if self._closed:
|
| 670 |
+
return
|
| 671 |
+
if self._debug:
|
| 672 |
+
logger.debug("Close %r", self)
|
| 673 |
+
self._closed = True
|
| 674 |
+
self._ready.clear()
|
| 675 |
+
self._scheduled.clear()
|
| 676 |
+
self._executor_shutdown_called = True
|
| 677 |
+
executor = self._default_executor
|
| 678 |
+
if executor is not None:
|
| 679 |
+
self._default_executor = None
|
| 680 |
+
executor.shutdown(wait=False)
|
| 681 |
+
|
| 682 |
+
def is_closed(self):
|
| 683 |
+
"""Returns True if the event loop was closed."""
|
| 684 |
+
return self._closed
|
| 685 |
+
|
| 686 |
+
def __del__(self, _warn=warnings.warn):
|
| 687 |
+
if not self.is_closed():
|
| 688 |
+
_warn(f"unclosed event loop {self!r}", ResourceWarning, source=self)
|
| 689 |
+
if not self.is_running():
|
| 690 |
+
self.close()
|
| 691 |
+
|
| 692 |
+
def is_running(self):
|
| 693 |
+
"""Returns True if the event loop is running."""
|
| 694 |
+
return (self._thread_id is not None)
|
| 695 |
+
|
| 696 |
+
def time(self):
|
| 697 |
+
"""Return the time according to the event loop's clock.
|
| 698 |
+
|
| 699 |
+
This is a float expressed in seconds since an epoch, but the
|
| 700 |
+
epoch, precision, accuracy and drift are unspecified and may
|
| 701 |
+
differ per event loop.
|
| 702 |
+
"""
|
| 703 |
+
return time.monotonic()
|
| 704 |
+
|
| 705 |
+
def call_later(self, delay, callback, *args, context=None):
|
| 706 |
+
"""Arrange for a callback to be called at a given time.
|
| 707 |
+
|
| 708 |
+
Return a Handle: an opaque object with a cancel() method that
|
| 709 |
+
can be used to cancel the call.
|
| 710 |
+
|
| 711 |
+
The delay can be an int or float, expressed in seconds. It is
|
| 712 |
+
always relative to the current time.
|
| 713 |
+
|
| 714 |
+
Each callback will be called exactly once. If two callbacks
|
| 715 |
+
are scheduled for exactly the same time, it undefined which
|
| 716 |
+
will be called first.
|
| 717 |
+
|
| 718 |
+
Any positional arguments after the callback will be passed to
|
| 719 |
+
the callback when it is called.
|
| 720 |
+
"""
|
| 721 |
+
timer = self.call_at(self.time() + delay, callback, *args,
|
| 722 |
+
context=context)
|
| 723 |
+
if timer._source_traceback:
|
| 724 |
+
del timer._source_traceback[-1]
|
| 725 |
+
return timer
|
| 726 |
+
|
| 727 |
+
def call_at(self, when, callback, *args, context=None):
|
| 728 |
+
"""Like call_later(), but uses an absolute time.
|
| 729 |
+
|
| 730 |
+
Absolute time corresponds to the event loop's time() method.
|
| 731 |
+
"""
|
| 732 |
+
self._check_closed()
|
| 733 |
+
if self._debug:
|
| 734 |
+
self._check_thread()
|
| 735 |
+
self._check_callback(callback, 'call_at')
|
| 736 |
+
timer = events.TimerHandle(when, callback, args, self, context)
|
| 737 |
+
if timer._source_traceback:
|
| 738 |
+
del timer._source_traceback[-1]
|
| 739 |
+
heapq.heappush(self._scheduled, timer)
|
| 740 |
+
timer._scheduled = True
|
| 741 |
+
return timer
|
| 742 |
+
|
| 743 |
+
def call_soon(self, callback, *args, context=None):
|
| 744 |
+
"""Arrange for a callback to be called as soon as possible.
|
| 745 |
+
|
| 746 |
+
This operates as a FIFO queue: callbacks are called in the
|
| 747 |
+
order in which they are registered. Each callback will be
|
| 748 |
+
called exactly once.
|
| 749 |
+
|
| 750 |
+
Any positional arguments after the callback will be passed to
|
| 751 |
+
the callback when it is called.
|
| 752 |
+
"""
|
| 753 |
+
self._check_closed()
|
| 754 |
+
if self._debug:
|
| 755 |
+
self._check_thread()
|
| 756 |
+
self._check_callback(callback, 'call_soon')
|
| 757 |
+
handle = self._call_soon(callback, args, context)
|
| 758 |
+
if handle._source_traceback:
|
| 759 |
+
del handle._source_traceback[-1]
|
| 760 |
+
return handle
|
| 761 |
+
|
| 762 |
+
def _check_callback(self, callback, method):
|
| 763 |
+
if (coroutines.iscoroutine(callback) or
|
| 764 |
+
coroutines.iscoroutinefunction(callback)):
|
| 765 |
+
raise TypeError(
|
| 766 |
+
f"coroutines cannot be used with {method}()")
|
| 767 |
+
if not callable(callback):
|
| 768 |
+
raise TypeError(
|
| 769 |
+
f'a callable object was expected by {method}(), '
|
| 770 |
+
f'got {callback!r}')
|
| 771 |
+
|
| 772 |
+
def _call_soon(self, callback, args, context):
|
| 773 |
+
handle = events.Handle(callback, args, self, context)
|
| 774 |
+
if handle._source_traceback:
|
| 775 |
+
del handle._source_traceback[-1]
|
| 776 |
+
self._ready.append(handle)
|
| 777 |
+
return handle
|
| 778 |
+
|
| 779 |
+
def _check_thread(self):
|
| 780 |
+
"""Check that the current thread is the thread running the event loop.
|
| 781 |
+
|
| 782 |
+
Non-thread-safe methods of this class make this assumption and will
|
| 783 |
+
likely behave incorrectly when the assumption is violated.
|
| 784 |
+
|
| 785 |
+
Should only be called when (self._debug == True). The caller is
|
| 786 |
+
responsible for checking this condition for performance reasons.
|
| 787 |
+
"""
|
| 788 |
+
if self._thread_id is None:
|
| 789 |
+
return
|
| 790 |
+
thread_id = threading.get_ident()
|
| 791 |
+
if thread_id != self._thread_id:
|
| 792 |
+
raise RuntimeError(
|
| 793 |
+
"Non-thread-safe operation invoked on an event loop other "
|
| 794 |
+
"than the current one")
|
| 795 |
+
|
| 796 |
+
def call_soon_threadsafe(self, callback, *args, context=None):
|
| 797 |
+
"""Like call_soon(), but thread-safe."""
|
| 798 |
+
self._check_closed()
|
| 799 |
+
if self._debug:
|
| 800 |
+
self._check_callback(callback, 'call_soon_threadsafe')
|
| 801 |
+
handle = self._call_soon(callback, args, context)
|
| 802 |
+
if handle._source_traceback:
|
| 803 |
+
del handle._source_traceback[-1]
|
| 804 |
+
self._write_to_self()
|
| 805 |
+
return handle
|
| 806 |
+
|
| 807 |
+
def run_in_executor(self, executor, func, *args):
|
| 808 |
+
self._check_closed()
|
| 809 |
+
if self._debug:
|
| 810 |
+
self._check_callback(func, 'run_in_executor')
|
| 811 |
+
if executor is None:
|
| 812 |
+
executor = self._default_executor
|
| 813 |
+
# Only check when the default executor is being used
|
| 814 |
+
self._check_default_executor()
|
| 815 |
+
if executor is None:
|
| 816 |
+
executor = concurrent.futures.ThreadPoolExecutor(
|
| 817 |
+
thread_name_prefix='asyncio'
|
| 818 |
+
)
|
| 819 |
+
self._default_executor = executor
|
| 820 |
+
return futures.wrap_future(
|
| 821 |
+
executor.submit(func, *args), loop=self)
|
| 822 |
+
|
| 823 |
+
def set_default_executor(self, executor):
|
| 824 |
+
if not isinstance(executor, concurrent.futures.ThreadPoolExecutor):
|
| 825 |
+
warnings.warn(
|
| 826 |
+
'Using the default executor that is not an instance of '
|
| 827 |
+
'ThreadPoolExecutor is deprecated and will be prohibited '
|
| 828 |
+
'in Python 3.9',
|
| 829 |
+
DeprecationWarning, 2)
|
| 830 |
+
self._default_executor = executor
|
| 831 |
+
|
| 832 |
+
def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
|
| 833 |
+
msg = [f"{host}:{port!r}"]
|
| 834 |
+
if family:
|
| 835 |
+
msg.append(f'family={family!r}')
|
| 836 |
+
if type:
|
| 837 |
+
msg.append(f'type={type!r}')
|
| 838 |
+
if proto:
|
| 839 |
+
msg.append(f'proto={proto!r}')
|
| 840 |
+
if flags:
|
| 841 |
+
msg.append(f'flags={flags!r}')
|
| 842 |
+
msg = ', '.join(msg)
|
| 843 |
+
logger.debug('Get address info %s', msg)
|
| 844 |
+
|
| 845 |
+
t0 = self.time()
|
| 846 |
+
addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
|
| 847 |
+
dt = self.time() - t0
|
| 848 |
+
|
| 849 |
+
msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
|
| 850 |
+
if dt >= self.slow_callback_duration:
|
| 851 |
+
logger.info(msg)
|
| 852 |
+
else:
|
| 853 |
+
logger.debug(msg)
|
| 854 |
+
return addrinfo
|
| 855 |
+
|
| 856 |
+
async def getaddrinfo(self, host, port, *,
|
| 857 |
+
family=0, type=0, proto=0, flags=0):
|
| 858 |
+
if self._debug:
|
| 859 |
+
getaddr_func = self._getaddrinfo_debug
|
| 860 |
+
else:
|
| 861 |
+
getaddr_func = socket.getaddrinfo
|
| 862 |
+
|
| 863 |
+
return await self.run_in_executor(
|
| 864 |
+
None, getaddr_func, host, port, family, type, proto, flags)
|
| 865 |
+
|
| 866 |
+
async def getnameinfo(self, sockaddr, flags=0):
|
| 867 |
+
return await self.run_in_executor(
|
| 868 |
+
None, socket.getnameinfo, sockaddr, flags)
|
| 869 |
+
|
| 870 |
+
async def sock_sendfile(self, sock, file, offset=0, count=None,
|
| 871 |
+
*, fallback=True):
|
| 872 |
+
if self._debug and sock.gettimeout() != 0:
|
| 873 |
+
raise ValueError("the socket must be non-blocking")
|
| 874 |
+
_check_ssl_socket(sock)
|
| 875 |
+
self._check_sendfile_params(sock, file, offset, count)
|
| 876 |
+
try:
|
| 877 |
+
return await self._sock_sendfile_native(sock, file,
|
| 878 |
+
offset, count)
|
| 879 |
+
except exceptions.SendfileNotAvailableError as exc:
|
| 880 |
+
if not fallback:
|
| 881 |
+
raise
|
| 882 |
+
return await self._sock_sendfile_fallback(sock, file,
|
| 883 |
+
offset, count)
|
| 884 |
+
|
| 885 |
+
async def _sock_sendfile_native(self, sock, file, offset, count):
|
| 886 |
+
# NB: sendfile syscall is not supported for SSL sockets and
|
| 887 |
+
# non-mmap files even if sendfile is supported by OS
|
| 888 |
+
raise exceptions.SendfileNotAvailableError(
|
| 889 |
+
f"syscall sendfile is not available for socket {sock!r} "
|
| 890 |
+
f"and file {file!r} combination")
|
| 891 |
+
|
| 892 |
+
async def _sock_sendfile_fallback(self, sock, file, offset, count):
|
| 893 |
+
if offset:
|
| 894 |
+
file.seek(offset)
|
| 895 |
+
blocksize = (
|
| 896 |
+
min(count, constants.SENDFILE_FALLBACK_READBUFFER_SIZE)
|
| 897 |
+
if count else constants.SENDFILE_FALLBACK_READBUFFER_SIZE
|
| 898 |
+
)
|
| 899 |
+
buf = bytearray(blocksize)
|
| 900 |
+
total_sent = 0
|
| 901 |
+
try:
|
| 902 |
+
while True:
|
| 903 |
+
if count:
|
| 904 |
+
blocksize = min(count - total_sent, blocksize)
|
| 905 |
+
if blocksize <= 0:
|
| 906 |
+
break
|
| 907 |
+
view = memoryview(buf)[:blocksize]
|
| 908 |
+
read = await self.run_in_executor(None, file.readinto, view)
|
| 909 |
+
if not read:
|
| 910 |
+
break # EOF
|
| 911 |
+
await self.sock_sendall(sock, view[:read])
|
| 912 |
+
total_sent += read
|
| 913 |
+
return total_sent
|
| 914 |
+
finally:
|
| 915 |
+
if total_sent > 0 and hasattr(file, 'seek'):
|
| 916 |
+
file.seek(offset + total_sent)
|
| 917 |
+
|
| 918 |
+
def _check_sendfile_params(self, sock, file, offset, count):
|
| 919 |
+
if 'b' not in getattr(file, 'mode', 'b'):
|
| 920 |
+
raise ValueError("file should be opened in binary mode")
|
| 921 |
+
if not sock.type == socket.SOCK_STREAM:
|
| 922 |
+
raise ValueError("only SOCK_STREAM type sockets are supported")
|
| 923 |
+
if count is not None:
|
| 924 |
+
if not isinstance(count, int):
|
| 925 |
+
raise TypeError(
|
| 926 |
+
"count must be a positive integer (got {!r})".format(count))
|
| 927 |
+
if count <= 0:
|
| 928 |
+
raise ValueError(
|
| 929 |
+
"count must be a positive integer (got {!r})".format(count))
|
| 930 |
+
if not isinstance(offset, int):
|
| 931 |
+
raise TypeError(
|
| 932 |
+
"offset must be a non-negative integer (got {!r})".format(
|
| 933 |
+
offset))
|
| 934 |
+
if offset < 0:
|
| 935 |
+
raise ValueError(
|
| 936 |
+
"offset must be a non-negative integer (got {!r})".format(
|
| 937 |
+
offset))
|
| 938 |
+
|
| 939 |
+
async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None):
|
| 940 |
+
"""Create, bind and connect one socket."""
|
| 941 |
+
my_exceptions = []
|
| 942 |
+
exceptions.append(my_exceptions)
|
| 943 |
+
family, type_, proto, _, address = addr_info
|
| 944 |
+
sock = None
|
| 945 |
+
try:
|
| 946 |
+
sock = socket.socket(family=family, type=type_, proto=proto)
|
| 947 |
+
sock.setblocking(False)
|
| 948 |
+
if local_addr_infos is not None:
|
| 949 |
+
for lfamily, _, _, _, laddr in local_addr_infos:
|
| 950 |
+
# skip local addresses of different family
|
| 951 |
+
if lfamily != family:
|
| 952 |
+
continue
|
| 953 |
+
try:
|
| 954 |
+
sock.bind(laddr)
|
| 955 |
+
break
|
| 956 |
+
except OSError as exc:
|
| 957 |
+
msg = (
|
| 958 |
+
f'error while attempting to bind on '
|
| 959 |
+
f'address {laddr!r}: '
|
| 960 |
+
f'{exc.strerror.lower()}'
|
| 961 |
+
)
|
| 962 |
+
exc = OSError(exc.errno, msg)
|
| 963 |
+
my_exceptions.append(exc)
|
| 964 |
+
else: # all bind attempts failed
|
| 965 |
+
if my_exceptions:
|
| 966 |
+
raise my_exceptions.pop()
|
| 967 |
+
else:
|
| 968 |
+
raise OSError(f"no matching local address with {family=} found")
|
| 969 |
+
await self.sock_connect(sock, address)
|
| 970 |
+
return sock
|
| 971 |
+
except OSError as exc:
|
| 972 |
+
my_exceptions.append(exc)
|
| 973 |
+
if sock is not None:
|
| 974 |
+
sock.close()
|
| 975 |
+
raise
|
| 976 |
+
except:
|
| 977 |
+
if sock is not None:
|
| 978 |
+
sock.close()
|
| 979 |
+
raise
|
| 980 |
+
finally:
|
| 981 |
+
exceptions = my_exceptions = None
|
| 982 |
+
|
| 983 |
+
async def create_connection(
|
| 984 |
+
self, protocol_factory, host=None, port=None,
|
| 985 |
+
*, ssl=None, family=0,
|
| 986 |
+
proto=0, flags=0, sock=None,
|
| 987 |
+
local_addr=None, server_hostname=None,
|
| 988 |
+
ssl_handshake_timeout=None,
|
| 989 |
+
happy_eyeballs_delay=None, interleave=None):
|
| 990 |
+
"""Connect to a TCP server.
|
| 991 |
+
|
| 992 |
+
Create a streaming transport connection to a given internet host and
|
| 993 |
+
port: socket family AF_INET or socket.AF_INET6 depending on host (or
|
| 994 |
+
family if specified), socket type SOCK_STREAM. protocol_factory must be
|
| 995 |
+
a callable returning a protocol instance.
|
| 996 |
+
|
| 997 |
+
This method is a coroutine which will try to establish the connection
|
| 998 |
+
in the background. When successful, the coroutine returns a
|
| 999 |
+
(transport, protocol) pair.
|
| 1000 |
+
"""
|
| 1001 |
+
if server_hostname is not None and not ssl:
|
| 1002 |
+
raise ValueError('server_hostname is only meaningful with ssl')
|
| 1003 |
+
|
| 1004 |
+
if server_hostname is None and ssl:
|
| 1005 |
+
# Use host as default for server_hostname. It is an error
|
| 1006 |
+
# if host is empty or not set, e.g. when an
|
| 1007 |
+
# already-connected socket was passed or when only a port
|
| 1008 |
+
# is given. To avoid this error, you can pass
|
| 1009 |
+
# server_hostname='' -- this will bypass the hostname
|
| 1010 |
+
# check. (This also means that if host is a numeric
|
| 1011 |
+
# IP/IPv6 address, we will attempt to verify that exact
|
| 1012 |
+
# address; this will probably fail, but it is possible to
|
| 1013 |
+
# create a certificate for a specific IP address, so we
|
| 1014 |
+
# don't judge it here.)
|
| 1015 |
+
if not host:
|
| 1016 |
+
raise ValueError('You must set server_hostname '
|
| 1017 |
+
'when using ssl without a host')
|
| 1018 |
+
server_hostname = host
|
| 1019 |
+
|
| 1020 |
+
if ssl_handshake_timeout is not None and not ssl:
|
| 1021 |
+
raise ValueError(
|
| 1022 |
+
'ssl_handshake_timeout is only meaningful with ssl')
|
| 1023 |
+
|
| 1024 |
+
if sock is not None:
|
| 1025 |
+
_check_ssl_socket(sock)
|
| 1026 |
+
|
| 1027 |
+
if happy_eyeballs_delay is not None and interleave is None:
|
| 1028 |
+
# If using happy eyeballs, default to interleave addresses by family
|
| 1029 |
+
interleave = 1
|
| 1030 |
+
|
| 1031 |
+
if host is not None or port is not None:
|
| 1032 |
+
if sock is not None:
|
| 1033 |
+
raise ValueError(
|
| 1034 |
+
'host/port and sock can not be specified at the same time')
|
| 1035 |
+
|
| 1036 |
+
infos = await self._ensure_resolved(
|
| 1037 |
+
(host, port), family=family,
|
| 1038 |
+
type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
|
| 1039 |
+
if not infos:
|
| 1040 |
+
raise OSError('getaddrinfo() returned empty list')
|
| 1041 |
+
|
| 1042 |
+
if local_addr is not None:
|
| 1043 |
+
laddr_infos = await self._ensure_resolved(
|
| 1044 |
+
local_addr, family=family,
|
| 1045 |
+
type=socket.SOCK_STREAM, proto=proto,
|
| 1046 |
+
flags=flags, loop=self)
|
| 1047 |
+
if not laddr_infos:
|
| 1048 |
+
raise OSError('getaddrinfo() returned empty list')
|
| 1049 |
+
else:
|
| 1050 |
+
laddr_infos = None
|
| 1051 |
+
|
| 1052 |
+
if interleave:
|
| 1053 |
+
infos = _interleave_addrinfos(infos, interleave)
|
| 1054 |
+
|
| 1055 |
+
exceptions = []
|
| 1056 |
+
if happy_eyeballs_delay is None:
|
| 1057 |
+
# not using happy eyeballs
|
| 1058 |
+
for addrinfo in infos:
|
| 1059 |
+
try:
|
| 1060 |
+
sock = await self._connect_sock(
|
| 1061 |
+
exceptions, addrinfo, laddr_infos)
|
| 1062 |
+
break
|
| 1063 |
+
except OSError:
|
| 1064 |
+
continue
|
| 1065 |
+
else: # using happy eyeballs
|
| 1066 |
+
sock, _, _ = await staggered.staggered_race(
|
| 1067 |
+
(functools.partial(self._connect_sock,
|
| 1068 |
+
exceptions, addrinfo, laddr_infos)
|
| 1069 |
+
for addrinfo in infos),
|
| 1070 |
+
happy_eyeballs_delay, loop=self)
|
| 1071 |
+
|
| 1072 |
+
if sock is None:
|
| 1073 |
+
exceptions = [exc for sub in exceptions for exc in sub]
|
| 1074 |
+
try:
|
| 1075 |
+
if len(exceptions) == 1:
|
| 1076 |
+
raise exceptions[0]
|
| 1077 |
+
else:
|
| 1078 |
+
# If they all have the same str(), raise one.
|
| 1079 |
+
model = str(exceptions[0])
|
| 1080 |
+
if all(str(exc) == model for exc in exceptions):
|
| 1081 |
+
raise exceptions[0]
|
| 1082 |
+
# Raise a combined exception so the user can see all
|
| 1083 |
+
# the various error messages.
|
| 1084 |
+
raise OSError('Multiple exceptions: {}'.format(
|
| 1085 |
+
', '.join(str(exc) for exc in exceptions)))
|
| 1086 |
+
finally:
|
| 1087 |
+
exceptions = None
|
| 1088 |
+
|
| 1089 |
+
else:
|
| 1090 |
+
if sock is None:
|
| 1091 |
+
raise ValueError(
|
| 1092 |
+
'host and port was not specified and no sock specified')
|
| 1093 |
+
if sock.type != socket.SOCK_STREAM:
|
| 1094 |
+
# We allow AF_INET, AF_INET6, AF_UNIX as long as they
|
| 1095 |
+
# are SOCK_STREAM.
|
| 1096 |
+
# We support passing AF_UNIX sockets even though we have
|
| 1097 |
+
# a dedicated API for that: create_unix_connection.
|
| 1098 |
+
# Disallowing AF_UNIX in this method, breaks backwards
|
| 1099 |
+
# compatibility.
|
| 1100 |
+
raise ValueError(
|
| 1101 |
+
f'A Stream Socket was expected, got {sock!r}')
|
| 1102 |
+
|
| 1103 |
+
transport, protocol = await self._create_connection_transport(
|
| 1104 |
+
sock, protocol_factory, ssl, server_hostname,
|
| 1105 |
+
ssl_handshake_timeout=ssl_handshake_timeout)
|
| 1106 |
+
if self._debug:
|
| 1107 |
+
# Get the socket from the transport because SSL transport closes
|
| 1108 |
+
# the old socket and creates a new SSL socket
|
| 1109 |
+
sock = transport.get_extra_info('socket')
|
| 1110 |
+
logger.debug("%r connected to %s:%r: (%r, %r)",
|
| 1111 |
+
sock, host, port, transport, protocol)
|
| 1112 |
+
return transport, protocol
|
| 1113 |
+
|
| 1114 |
+
async def _create_connection_transport(
|
| 1115 |
+
self, sock, protocol_factory, ssl,
|
| 1116 |
+
server_hostname, server_side=False,
|
| 1117 |
+
ssl_handshake_timeout=None):
|
| 1118 |
+
|
| 1119 |
+
sock.setblocking(False)
|
| 1120 |
+
|
| 1121 |
+
protocol = protocol_factory()
|
| 1122 |
+
waiter = self.create_future()
|
| 1123 |
+
if ssl:
|
| 1124 |
+
sslcontext = None if isinstance(ssl, bool) else ssl
|
| 1125 |
+
transport = self._make_ssl_transport(
|
| 1126 |
+
sock, protocol, sslcontext, waiter,
|
| 1127 |
+
server_side=server_side, server_hostname=server_hostname,
|
| 1128 |
+
ssl_handshake_timeout=ssl_handshake_timeout)
|
| 1129 |
+
else:
|
| 1130 |
+
transport = self._make_socket_transport(sock, protocol, waiter)
|
| 1131 |
+
|
| 1132 |
+
try:
|
| 1133 |
+
await waiter
|
| 1134 |
+
except:
|
| 1135 |
+
transport.close()
|
| 1136 |
+
raise
|
| 1137 |
+
|
| 1138 |
+
return transport, protocol
|
| 1139 |
+
|
| 1140 |
+
async def sendfile(self, transport, file, offset=0, count=None,
|
| 1141 |
+
*, fallback=True):
|
| 1142 |
+
"""Send a file to transport.
|
| 1143 |
+
|
| 1144 |
+
Return the total number of bytes which were sent.
|
| 1145 |
+
|
| 1146 |
+
The method uses high-performance os.sendfile if available.
|
| 1147 |
+
|
| 1148 |
+
file must be a regular file object opened in binary mode.
|
| 1149 |
+
|
| 1150 |
+
offset tells from where to start reading the file. If specified,
|
| 1151 |
+
count is the total number of bytes to transmit as opposed to
|
| 1152 |
+
sending the file until EOF is reached. File position is updated on
|
| 1153 |
+
return or also in case of error in which case file.tell()
|
| 1154 |
+
can be used to figure out the number of bytes
|
| 1155 |
+
which were sent.
|
| 1156 |
+
|
| 1157 |
+
fallback set to True makes asyncio to manually read and send
|
| 1158 |
+
the file when the platform does not support the sendfile syscall
|
| 1159 |
+
(e.g. Windows or SSL socket on Unix).
|
| 1160 |
+
|
| 1161 |
+
Raise SendfileNotAvailableError if the system does not support
|
| 1162 |
+
sendfile syscall and fallback is False.
|
| 1163 |
+
"""
|
| 1164 |
+
if transport.is_closing():
|
| 1165 |
+
raise RuntimeError("Transport is closing")
|
| 1166 |
+
mode = getattr(transport, '_sendfile_compatible',
|
| 1167 |
+
constants._SendfileMode.UNSUPPORTED)
|
| 1168 |
+
if mode is constants._SendfileMode.UNSUPPORTED:
|
| 1169 |
+
raise RuntimeError(
|
| 1170 |
+
f"sendfile is not supported for transport {transport!r}")
|
| 1171 |
+
if mode is constants._SendfileMode.TRY_NATIVE:
|
| 1172 |
+
try:
|
| 1173 |
+
return await self._sendfile_native(transport, file,
|
| 1174 |
+
offset, count)
|
| 1175 |
+
except exceptions.SendfileNotAvailableError as exc:
|
| 1176 |
+
if not fallback:
|
| 1177 |
+
raise
|
| 1178 |
+
|
| 1179 |
+
if not fallback:
|
| 1180 |
+
raise RuntimeError(
|
| 1181 |
+
f"fallback is disabled and native sendfile is not "
|
| 1182 |
+
f"supported for transport {transport!r}")
|
| 1183 |
+
|
| 1184 |
+
return await self._sendfile_fallback(transport, file,
|
| 1185 |
+
offset, count)
|
| 1186 |
+
|
| 1187 |
+
async def _sendfile_native(self, transp, file, offset, count):
|
| 1188 |
+
raise exceptions.SendfileNotAvailableError(
|
| 1189 |
+
"sendfile syscall is not supported")
|
| 1190 |
+
|
| 1191 |
+
async def _sendfile_fallback(self, transp, file, offset, count):
|
| 1192 |
+
if offset:
|
| 1193 |
+
file.seek(offset)
|
| 1194 |
+
blocksize = min(count, 16384) if count else 16384
|
| 1195 |
+
buf = bytearray(blocksize)
|
| 1196 |
+
total_sent = 0
|
| 1197 |
+
proto = _SendfileFallbackProtocol(transp)
|
| 1198 |
+
try:
|
| 1199 |
+
while True:
|
| 1200 |
+
if count:
|
| 1201 |
+
blocksize = min(count - total_sent, blocksize)
|
| 1202 |
+
if blocksize <= 0:
|
| 1203 |
+
return total_sent
|
| 1204 |
+
view = memoryview(buf)[:blocksize]
|
| 1205 |
+
read = await self.run_in_executor(None, file.readinto, view)
|
| 1206 |
+
if not read:
|
| 1207 |
+
return total_sent # EOF
|
| 1208 |
+
await proto.drain()
|
| 1209 |
+
transp.write(view[:read])
|
| 1210 |
+
total_sent += read
|
| 1211 |
+
finally:
|
| 1212 |
+
if total_sent > 0 and hasattr(file, 'seek'):
|
| 1213 |
+
file.seek(offset + total_sent)
|
| 1214 |
+
await proto.restore()
|
| 1215 |
+
|
| 1216 |
+
async def start_tls(self, transport, protocol, sslcontext, *,
|
| 1217 |
+
server_side=False,
|
| 1218 |
+
server_hostname=None,
|
| 1219 |
+
ssl_handshake_timeout=None):
|
| 1220 |
+
"""Upgrade transport to TLS.
|
| 1221 |
+
|
| 1222 |
+
Return a new transport that *protocol* should start using
|
| 1223 |
+
immediately.
|
| 1224 |
+
"""
|
| 1225 |
+
if ssl is None:
|
| 1226 |
+
raise RuntimeError('Python ssl module is not available')
|
| 1227 |
+
|
| 1228 |
+
if not isinstance(sslcontext, ssl.SSLContext):
|
| 1229 |
+
raise TypeError(
|
| 1230 |
+
f'sslcontext is expected to be an instance of ssl.SSLContext, '
|
| 1231 |
+
f'got {sslcontext!r}')
|
| 1232 |
+
|
| 1233 |
+
if not getattr(transport, '_start_tls_compatible', False):
|
| 1234 |
+
raise TypeError(
|
| 1235 |
+
f'transport {transport!r} is not supported by start_tls()')
|
| 1236 |
+
|
| 1237 |
+
waiter = self.create_future()
|
| 1238 |
+
ssl_protocol = sslproto.SSLProtocol(
|
| 1239 |
+
self, protocol, sslcontext, waiter,
|
| 1240 |
+
server_side, server_hostname,
|
| 1241 |
+
ssl_handshake_timeout=ssl_handshake_timeout,
|
| 1242 |
+
call_connection_made=False)
|
| 1243 |
+
|
| 1244 |
+
# Pause early so that "ssl_protocol.data_received()" doesn't
|
| 1245 |
+
# have a chance to get called before "ssl_protocol.connection_made()".
|
| 1246 |
+
transport.pause_reading()
|
| 1247 |
+
|
| 1248 |
+
transport.set_protocol(ssl_protocol)
|
| 1249 |
+
conmade_cb = self.call_soon(ssl_protocol.connection_made, transport)
|
| 1250 |
+
resume_cb = self.call_soon(transport.resume_reading)
|
| 1251 |
+
|
| 1252 |
+
try:
|
| 1253 |
+
await waiter
|
| 1254 |
+
except BaseException:
|
| 1255 |
+
transport.close()
|
| 1256 |
+
conmade_cb.cancel()
|
| 1257 |
+
resume_cb.cancel()
|
| 1258 |
+
raise
|
| 1259 |
+
|
| 1260 |
+
return ssl_protocol._app_transport
|
| 1261 |
+
|
| 1262 |
+
async def create_datagram_endpoint(self, protocol_factory,
|
| 1263 |
+
local_addr=None, remote_addr=None, *,
|
| 1264 |
+
family=0, proto=0, flags=0,
|
| 1265 |
+
reuse_address=_unset, reuse_port=None,
|
| 1266 |
+
allow_broadcast=None, sock=None):
|
| 1267 |
+
"""Create datagram connection."""
|
| 1268 |
+
if sock is not None:
|
| 1269 |
+
if sock.type != socket.SOCK_DGRAM:
|
| 1270 |
+
raise ValueError(
|
| 1271 |
+
f'A UDP Socket was expected, got {sock!r}')
|
| 1272 |
+
if (local_addr or remote_addr or
|
| 1273 |
+
family or proto or flags or
|
| 1274 |
+
reuse_port or allow_broadcast):
|
| 1275 |
+
# show the problematic kwargs in exception msg
|
| 1276 |
+
opts = dict(local_addr=local_addr, remote_addr=remote_addr,
|
| 1277 |
+
family=family, proto=proto, flags=flags,
|
| 1278 |
+
reuse_address=reuse_address, reuse_port=reuse_port,
|
| 1279 |
+
allow_broadcast=allow_broadcast)
|
| 1280 |
+
problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
|
| 1281 |
+
raise ValueError(
|
| 1282 |
+
f'socket modifier keyword arguments can not be used '
|
| 1283 |
+
f'when sock is specified. ({problems})')
|
| 1284 |
+
sock.setblocking(False)
|
| 1285 |
+
r_addr = None
|
| 1286 |
+
else:
|
| 1287 |
+
if not (local_addr or remote_addr):
|
| 1288 |
+
if family == 0:
|
| 1289 |
+
raise ValueError('unexpected address family')
|
| 1290 |
+
addr_pairs_info = (((family, proto), (None, None)),)
|
| 1291 |
+
elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
|
| 1292 |
+
for addr in (local_addr, remote_addr):
|
| 1293 |
+
if addr is not None and not isinstance(addr, str):
|
| 1294 |
+
raise TypeError('string is expected')
|
| 1295 |
+
|
| 1296 |
+
if local_addr and local_addr[0] not in (0, '\x00'):
|
| 1297 |
+
try:
|
| 1298 |
+
if stat.S_ISSOCK(os.stat(local_addr).st_mode):
|
| 1299 |
+
os.remove(local_addr)
|
| 1300 |
+
except FileNotFoundError:
|
| 1301 |
+
pass
|
| 1302 |
+
except OSError as err:
|
| 1303 |
+
# Directory may have permissions only to create socket.
|
| 1304 |
+
logger.error('Unable to check or remove stale UNIX '
|
| 1305 |
+
'socket %r: %r',
|
| 1306 |
+
local_addr, err)
|
| 1307 |
+
|
| 1308 |
+
addr_pairs_info = (((family, proto),
|
| 1309 |
+
(local_addr, remote_addr)), )
|
| 1310 |
+
else:
|
| 1311 |
+
# join address by (family, protocol)
|
| 1312 |
+
addr_infos = {} # Using order preserving dict
|
| 1313 |
+
for idx, addr in ((0, local_addr), (1, remote_addr)):
|
| 1314 |
+
if addr is not None:
|
| 1315 |
+
assert isinstance(addr, tuple) and len(addr) == 2, (
|
| 1316 |
+
'2-tuple is expected')
|
| 1317 |
+
|
| 1318 |
+
infos = await self._ensure_resolved(
|
| 1319 |
+
addr, family=family, type=socket.SOCK_DGRAM,
|
| 1320 |
+
proto=proto, flags=flags, loop=self)
|
| 1321 |
+
if not infos:
|
| 1322 |
+
raise OSError('getaddrinfo() returned empty list')
|
| 1323 |
+
|
| 1324 |
+
for fam, _, pro, _, address in infos:
|
| 1325 |
+
key = (fam, pro)
|
| 1326 |
+
if key not in addr_infos:
|
| 1327 |
+
addr_infos[key] = [None, None]
|
| 1328 |
+
addr_infos[key][idx] = address
|
| 1329 |
+
|
| 1330 |
+
# each addr has to have info for each (family, proto) pair
|
| 1331 |
+
addr_pairs_info = [
|
| 1332 |
+
(key, addr_pair) for key, addr_pair in addr_infos.items()
|
| 1333 |
+
if not ((local_addr and addr_pair[0] is None) or
|
| 1334 |
+
(remote_addr and addr_pair[1] is None))]
|
| 1335 |
+
|
| 1336 |
+
if not addr_pairs_info:
|
| 1337 |
+
raise ValueError('can not get address information')
|
| 1338 |
+
|
| 1339 |
+
exceptions = []
|
| 1340 |
+
|
| 1341 |
+
# bpo-37228
|
| 1342 |
+
if reuse_address is not _unset:
|
| 1343 |
+
if reuse_address:
|
| 1344 |
+
raise ValueError("Passing `reuse_address=True` is no "
|
| 1345 |
+
"longer supported, as the usage of "
|
| 1346 |
+
"SO_REUSEPORT in UDP poses a significant "
|
| 1347 |
+
"security concern.")
|
| 1348 |
+
else:
|
| 1349 |
+
warnings.warn("The *reuse_address* parameter has been "
|
| 1350 |
+
"deprecated as of 3.5.10 and is scheduled "
|
| 1351 |
+
"for removal in 3.11.", DeprecationWarning,
|
| 1352 |
+
stacklevel=2)
|
| 1353 |
+
|
| 1354 |
+
for ((family, proto),
|
| 1355 |
+
(local_address, remote_address)) in addr_pairs_info:
|
| 1356 |
+
sock = None
|
| 1357 |
+
r_addr = None
|
| 1358 |
+
try:
|
| 1359 |
+
sock = socket.socket(
|
| 1360 |
+
family=family, type=socket.SOCK_DGRAM, proto=proto)
|
| 1361 |
+
if reuse_port:
|
| 1362 |
+
_set_reuseport(sock)
|
| 1363 |
+
if allow_broadcast:
|
| 1364 |
+
sock.setsockopt(
|
| 1365 |
+
socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
| 1366 |
+
sock.setblocking(False)
|
| 1367 |
+
|
| 1368 |
+
if local_addr:
|
| 1369 |
+
sock.bind(local_address)
|
| 1370 |
+
if remote_addr:
|
| 1371 |
+
if not allow_broadcast:
|
| 1372 |
+
await self.sock_connect(sock, remote_address)
|
| 1373 |
+
r_addr = remote_address
|
| 1374 |
+
except OSError as exc:
|
| 1375 |
+
if sock is not None:
|
| 1376 |
+
sock.close()
|
| 1377 |
+
exceptions.append(exc)
|
| 1378 |
+
except:
|
| 1379 |
+
if sock is not None:
|
| 1380 |
+
sock.close()
|
| 1381 |
+
raise
|
| 1382 |
+
else:
|
| 1383 |
+
break
|
| 1384 |
+
else:
|
| 1385 |
+
raise exceptions[0]
|
| 1386 |
+
|
| 1387 |
+
protocol = protocol_factory()
|
| 1388 |
+
waiter = self.create_future()
|
| 1389 |
+
transport = self._make_datagram_transport(
|
| 1390 |
+
sock, protocol, r_addr, waiter)
|
| 1391 |
+
if self._debug:
|
| 1392 |
+
if local_addr:
|
| 1393 |
+
logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
|
| 1394 |
+
"created: (%r, %r)",
|
| 1395 |
+
local_addr, remote_addr, transport, protocol)
|
| 1396 |
+
else:
|
| 1397 |
+
logger.debug("Datagram endpoint remote_addr=%r created: "
|
| 1398 |
+
"(%r, %r)",
|
| 1399 |
+
remote_addr, transport, protocol)
|
| 1400 |
+
|
| 1401 |
+
try:
|
| 1402 |
+
await waiter
|
| 1403 |
+
except:
|
| 1404 |
+
transport.close()
|
| 1405 |
+
raise
|
| 1406 |
+
|
| 1407 |
+
return transport, protocol
|
| 1408 |
+
|
| 1409 |
+
async def _ensure_resolved(self, address, *,
|
| 1410 |
+
family=0, type=socket.SOCK_STREAM,
|
| 1411 |
+
proto=0, flags=0, loop):
|
| 1412 |
+
host, port = address[:2]
|
| 1413 |
+
info = _ipaddr_info(host, port, family, type, proto, *address[2:])
|
| 1414 |
+
if info is not None:
|
| 1415 |
+
# "host" is already a resolved IP.
|
| 1416 |
+
return [info]
|
| 1417 |
+
else:
|
| 1418 |
+
return await loop.getaddrinfo(host, port, family=family, type=type,
|
| 1419 |
+
proto=proto, flags=flags)
|
| 1420 |
+
|
| 1421 |
+
async def _create_server_getaddrinfo(self, host, port, family, flags):
|
| 1422 |
+
infos = await self._ensure_resolved((host, port), family=family,
|
| 1423 |
+
type=socket.SOCK_STREAM,
|
| 1424 |
+
flags=flags, loop=self)
|
| 1425 |
+
if not infos:
|
| 1426 |
+
raise OSError(f'getaddrinfo({host!r}) returned empty list')
|
| 1427 |
+
return infos
|
| 1428 |
+
|
| 1429 |
+
async def create_server(
|
| 1430 |
+
self, protocol_factory, host=None, port=None,
|
| 1431 |
+
*,
|
| 1432 |
+
family=socket.AF_UNSPEC,
|
| 1433 |
+
flags=socket.AI_PASSIVE,
|
| 1434 |
+
sock=None,
|
| 1435 |
+
backlog=100,
|
| 1436 |
+
ssl=None,
|
| 1437 |
+
reuse_address=None,
|
| 1438 |
+
reuse_port=None,
|
| 1439 |
+
ssl_handshake_timeout=None,
|
| 1440 |
+
start_serving=True):
|
| 1441 |
+
"""Create a TCP server.
|
| 1442 |
+
|
| 1443 |
+
The host parameter can be a string, in that case the TCP server is
|
| 1444 |
+
bound to host and port.
|
| 1445 |
+
|
| 1446 |
+
The host parameter can also be a sequence of strings and in that case
|
| 1447 |
+
the TCP server is bound to all hosts of the sequence. If a host
|
| 1448 |
+
appears multiple times (possibly indirectly e.g. when hostnames
|
| 1449 |
+
resolve to the same IP address), the server is only bound once to that
|
| 1450 |
+
host.
|
| 1451 |
+
|
| 1452 |
+
Return a Server object which can be used to stop the service.
|
| 1453 |
+
|
| 1454 |
+
This method is a coroutine.
|
| 1455 |
+
"""
|
| 1456 |
+
if isinstance(ssl, bool):
|
| 1457 |
+
raise TypeError('ssl argument must be an SSLContext or None')
|
| 1458 |
+
|
| 1459 |
+
if ssl_handshake_timeout is not None and ssl is None:
|
| 1460 |
+
raise ValueError(
|
| 1461 |
+
'ssl_handshake_timeout is only meaningful with ssl')
|
| 1462 |
+
|
| 1463 |
+
if sock is not None:
|
| 1464 |
+
_check_ssl_socket(sock)
|
| 1465 |
+
|
| 1466 |
+
if host is not None or port is not None:
|
| 1467 |
+
if sock is not None:
|
| 1468 |
+
raise ValueError(
|
| 1469 |
+
'host/port and sock can not be specified at the same time')
|
| 1470 |
+
|
| 1471 |
+
if reuse_address is None:
|
| 1472 |
+
reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
|
| 1473 |
+
sockets = []
|
| 1474 |
+
if host == '':
|
| 1475 |
+
hosts = [None]
|
| 1476 |
+
elif (isinstance(host, str) or
|
| 1477 |
+
not isinstance(host, collections.abc.Iterable)):
|
| 1478 |
+
hosts = [host]
|
| 1479 |
+
else:
|
| 1480 |
+
hosts = host
|
| 1481 |
+
|
| 1482 |
+
fs = [self._create_server_getaddrinfo(host, port, family=family,
|
| 1483 |
+
flags=flags)
|
| 1484 |
+
for host in hosts]
|
| 1485 |
+
infos = await tasks.gather(*fs)
|
| 1486 |
+
infos = set(itertools.chain.from_iterable(infos))
|
| 1487 |
+
|
| 1488 |
+
completed = False
|
| 1489 |
+
try:
|
| 1490 |
+
for res in infos:
|
| 1491 |
+
af, socktype, proto, canonname, sa = res
|
| 1492 |
+
try:
|
| 1493 |
+
sock = socket.socket(af, socktype, proto)
|
| 1494 |
+
except socket.error:
|
| 1495 |
+
# Assume it's a bad family/type/protocol combination.
|
| 1496 |
+
if self._debug:
|
| 1497 |
+
logger.warning('create_server() failed to create '
|
| 1498 |
+
'socket.socket(%r, %r, %r)',
|
| 1499 |
+
af, socktype, proto, exc_info=True)
|
| 1500 |
+
continue
|
| 1501 |
+
sockets.append(sock)
|
| 1502 |
+
if reuse_address:
|
| 1503 |
+
sock.setsockopt(
|
| 1504 |
+
socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
|
| 1505 |
+
if reuse_port:
|
| 1506 |
+
_set_reuseport(sock)
|
| 1507 |
+
# Disable IPv4/IPv6 dual stack support (enabled by
|
| 1508 |
+
# default on Linux) which makes a single socket
|
| 1509 |
+
# listen on both address families.
|
| 1510 |
+
if (_HAS_IPv6 and
|
| 1511 |
+
af == socket.AF_INET6 and
|
| 1512 |
+
hasattr(socket, 'IPPROTO_IPV6')):
|
| 1513 |
+
sock.setsockopt(socket.IPPROTO_IPV6,
|
| 1514 |
+
socket.IPV6_V6ONLY,
|
| 1515 |
+
True)
|
| 1516 |
+
try:
|
| 1517 |
+
sock.bind(sa)
|
| 1518 |
+
except OSError as err:
|
| 1519 |
+
raise OSError(err.errno, 'error while attempting '
|
| 1520 |
+
'to bind on address %r: %s'
|
| 1521 |
+
% (sa, err.strerror.lower())) from None
|
| 1522 |
+
completed = True
|
| 1523 |
+
finally:
|
| 1524 |
+
if not completed:
|
| 1525 |
+
for sock in sockets:
|
| 1526 |
+
sock.close()
|
| 1527 |
+
else:
|
| 1528 |
+
if sock is None:
|
| 1529 |
+
raise ValueError('Neither host/port nor sock were specified')
|
| 1530 |
+
if sock.type != socket.SOCK_STREAM:
|
| 1531 |
+
raise ValueError(f'A Stream Socket was expected, got {sock!r}')
|
| 1532 |
+
sockets = [sock]
|
| 1533 |
+
|
| 1534 |
+
for sock in sockets:
|
| 1535 |
+
sock.setblocking(False)
|
| 1536 |
+
|
| 1537 |
+
server = Server(self, sockets, protocol_factory,
|
| 1538 |
+
ssl, backlog, ssl_handshake_timeout)
|
| 1539 |
+
if start_serving:
|
| 1540 |
+
server._start_serving()
|
| 1541 |
+
# Skip one loop iteration so that all 'loop.add_reader'
|
| 1542 |
+
# go through.
|
| 1543 |
+
await tasks.sleep(0)
|
| 1544 |
+
|
| 1545 |
+
if self._debug:
|
| 1546 |
+
logger.info("%r is serving", server)
|
| 1547 |
+
return server
|
| 1548 |
+
|
| 1549 |
+
async def connect_accepted_socket(
|
| 1550 |
+
self, protocol_factory, sock,
|
| 1551 |
+
*, ssl=None,
|
| 1552 |
+
ssl_handshake_timeout=None):
|
| 1553 |
+
if sock.type != socket.SOCK_STREAM:
|
| 1554 |
+
raise ValueError(f'A Stream Socket was expected, got {sock!r}')
|
| 1555 |
+
|
| 1556 |
+
if ssl_handshake_timeout is not None and not ssl:
|
| 1557 |
+
raise ValueError(
|
| 1558 |
+
'ssl_handshake_timeout is only meaningful with ssl')
|
| 1559 |
+
|
| 1560 |
+
if sock is not None:
|
| 1561 |
+
_check_ssl_socket(sock)
|
| 1562 |
+
|
| 1563 |
+
transport, protocol = await self._create_connection_transport(
|
| 1564 |
+
sock, protocol_factory, ssl, '', server_side=True,
|
| 1565 |
+
ssl_handshake_timeout=ssl_handshake_timeout)
|
| 1566 |
+
if self._debug:
|
| 1567 |
+
# Get the socket from the transport because SSL transport closes
|
| 1568 |
+
# the old socket and creates a new SSL socket
|
| 1569 |
+
sock = transport.get_extra_info('socket')
|
| 1570 |
+
logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
|
| 1571 |
+
return transport, protocol
|
| 1572 |
+
|
| 1573 |
+
async def connect_read_pipe(self, protocol_factory, pipe):
|
| 1574 |
+
protocol = protocol_factory()
|
| 1575 |
+
waiter = self.create_future()
|
| 1576 |
+
transport = self._make_read_pipe_transport(pipe, protocol, waiter)
|
| 1577 |
+
|
| 1578 |
+
try:
|
| 1579 |
+
await waiter
|
| 1580 |
+
except:
|
| 1581 |
+
transport.close()
|
| 1582 |
+
raise
|
| 1583 |
+
|
| 1584 |
+
if self._debug:
|
| 1585 |
+
logger.debug('Read pipe %r connected: (%r, %r)',
|
| 1586 |
+
pipe.fileno(), transport, protocol)
|
| 1587 |
+
return transport, protocol
|
| 1588 |
+
|
| 1589 |
+
async def connect_write_pipe(self, protocol_factory, pipe):
|
| 1590 |
+
protocol = protocol_factory()
|
| 1591 |
+
waiter = self.create_future()
|
| 1592 |
+
transport = self._make_write_pipe_transport(pipe, protocol, waiter)
|
| 1593 |
+
|
| 1594 |
+
try:
|
| 1595 |
+
await waiter
|
| 1596 |
+
except:
|
| 1597 |
+
transport.close()
|
| 1598 |
+
raise
|
| 1599 |
+
|
| 1600 |
+
if self._debug:
|
| 1601 |
+
logger.debug('Write pipe %r connected: (%r, %r)',
|
| 1602 |
+
pipe.fileno(), transport, protocol)
|
| 1603 |
+
return transport, protocol
|
| 1604 |
+
|
| 1605 |
+
def _log_subprocess(self, msg, stdin, stdout, stderr):
|
| 1606 |
+
info = [msg]
|
| 1607 |
+
if stdin is not None:
|
| 1608 |
+
info.append(f'stdin={_format_pipe(stdin)}')
|
| 1609 |
+
if stdout is not None and stderr == subprocess.STDOUT:
|
| 1610 |
+
info.append(f'stdout=stderr={_format_pipe(stdout)}')
|
| 1611 |
+
else:
|
| 1612 |
+
if stdout is not None:
|
| 1613 |
+
info.append(f'stdout={_format_pipe(stdout)}')
|
| 1614 |
+
if stderr is not None:
|
| 1615 |
+
info.append(f'stderr={_format_pipe(stderr)}')
|
| 1616 |
+
logger.debug(' '.join(info))
|
| 1617 |
+
|
| 1618 |
+
async def subprocess_shell(self, protocol_factory, cmd, *,
|
| 1619 |
+
stdin=subprocess.PIPE,
|
| 1620 |
+
stdout=subprocess.PIPE,
|
| 1621 |
+
stderr=subprocess.PIPE,
|
| 1622 |
+
universal_newlines=False,
|
| 1623 |
+
shell=True, bufsize=0,
|
| 1624 |
+
encoding=None, errors=None, text=None,
|
| 1625 |
+
**kwargs):
|
| 1626 |
+
if not isinstance(cmd, (bytes, str)):
|
| 1627 |
+
raise ValueError("cmd must be a string")
|
| 1628 |
+
if universal_newlines:
|
| 1629 |
+
raise ValueError("universal_newlines must be False")
|
| 1630 |
+
if not shell:
|
| 1631 |
+
raise ValueError("shell must be True")
|
| 1632 |
+
if bufsize != 0:
|
| 1633 |
+
raise ValueError("bufsize must be 0")
|
| 1634 |
+
if text:
|
| 1635 |
+
raise ValueError("text must be False")
|
| 1636 |
+
if encoding is not None:
|
| 1637 |
+
raise ValueError("encoding must be None")
|
| 1638 |
+
if errors is not None:
|
| 1639 |
+
raise ValueError("errors must be None")
|
| 1640 |
+
|
| 1641 |
+
protocol = protocol_factory()
|
| 1642 |
+
debug_log = None
|
| 1643 |
+
if self._debug:
|
| 1644 |
+
# don't log parameters: they may contain sensitive information
|
| 1645 |
+
# (password) and may be too long
|
| 1646 |
+
debug_log = 'run shell command %r' % cmd
|
| 1647 |
+
self._log_subprocess(debug_log, stdin, stdout, stderr)
|
| 1648 |
+
transport = await self._make_subprocess_transport(
|
| 1649 |
+
protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
|
| 1650 |
+
if self._debug and debug_log is not None:
|
| 1651 |
+
logger.info('%s: %r', debug_log, transport)
|
| 1652 |
+
return transport, protocol
|
| 1653 |
+
|
| 1654 |
+
async def subprocess_exec(self, protocol_factory, program, *args,
|
| 1655 |
+
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
| 1656 |
+
stderr=subprocess.PIPE, universal_newlines=False,
|
| 1657 |
+
shell=False, bufsize=0,
|
| 1658 |
+
encoding=None, errors=None, text=None,
|
| 1659 |
+
**kwargs):
|
| 1660 |
+
if universal_newlines:
|
| 1661 |
+
raise ValueError("universal_newlines must be False")
|
| 1662 |
+
if shell:
|
| 1663 |
+
raise ValueError("shell must be False")
|
| 1664 |
+
if bufsize != 0:
|
| 1665 |
+
raise ValueError("bufsize must be 0")
|
| 1666 |
+
if text:
|
| 1667 |
+
raise ValueError("text must be False")
|
| 1668 |
+
if encoding is not None:
|
| 1669 |
+
raise ValueError("encoding must be None")
|
| 1670 |
+
if errors is not None:
|
| 1671 |
+
raise ValueError("errors must be None")
|
| 1672 |
+
|
| 1673 |
+
popen_args = (program,) + args
|
| 1674 |
+
protocol = protocol_factory()
|
| 1675 |
+
debug_log = None
|
| 1676 |
+
if self._debug:
|
| 1677 |
+
# don't log parameters: they may contain sensitive information
|
| 1678 |
+
# (password) and may be too long
|
| 1679 |
+
debug_log = f'execute program {program!r}'
|
| 1680 |
+
self._log_subprocess(debug_log, stdin, stdout, stderr)
|
| 1681 |
+
transport = await self._make_subprocess_transport(
|
| 1682 |
+
protocol, popen_args, False, stdin, stdout, stderr,
|
| 1683 |
+
bufsize, **kwargs)
|
| 1684 |
+
if self._debug and debug_log is not None:
|
| 1685 |
+
logger.info('%s: %r', debug_log, transport)
|
| 1686 |
+
return transport, protocol
|
| 1687 |
+
|
| 1688 |
+
def get_exception_handler(self):
|
| 1689 |
+
"""Return an exception handler, or None if the default one is in use.
|
| 1690 |
+
"""
|
| 1691 |
+
return self._exception_handler
|
| 1692 |
+
|
| 1693 |
+
def set_exception_handler(self, handler):
|
| 1694 |
+
"""Set handler as the new event loop exception handler.
|
| 1695 |
+
|
| 1696 |
+
If handler is None, the default exception handler will
|
| 1697 |
+
be set.
|
| 1698 |
+
|
| 1699 |
+
If handler is a callable object, it should have a
|
| 1700 |
+
signature matching '(loop, context)', where 'loop'
|
| 1701 |
+
will be a reference to the active event loop, 'context'
|
| 1702 |
+
will be a dict object (see `call_exception_handler()`
|
| 1703 |
+
documentation for details about context).
|
| 1704 |
+
"""
|
| 1705 |
+
if handler is not None and not callable(handler):
|
| 1706 |
+
raise TypeError(f'A callable object or None is expected, '
|
| 1707 |
+
f'got {handler!r}')
|
| 1708 |
+
self._exception_handler = handler
|
| 1709 |
+
|
| 1710 |
+
def default_exception_handler(self, context):
|
| 1711 |
+
"""Default exception handler.
|
| 1712 |
+
|
| 1713 |
+
This is called when an exception occurs and no exception
|
| 1714 |
+
handler is set, and can be called by a custom exception
|
| 1715 |
+
handler that wants to defer to the default behavior.
|
| 1716 |
+
|
| 1717 |
+
This default handler logs the error message and other
|
| 1718 |
+
context-dependent information. In debug mode, a truncated
|
| 1719 |
+
stack trace is also appended showing where the given object
|
| 1720 |
+
(e.g. a handle or future or task) was created, if any.
|
| 1721 |
+
|
| 1722 |
+
The context parameter has the same meaning as in
|
| 1723 |
+
`call_exception_handler()`.
|
| 1724 |
+
"""
|
| 1725 |
+
message = context.get('message')
|
| 1726 |
+
if not message:
|
| 1727 |
+
message = 'Unhandled exception in event loop'
|
| 1728 |
+
|
| 1729 |
+
exception = context.get('exception')
|
| 1730 |
+
if exception is not None:
|
| 1731 |
+
exc_info = (type(exception), exception, exception.__traceback__)
|
| 1732 |
+
else:
|
| 1733 |
+
exc_info = False
|
| 1734 |
+
|
| 1735 |
+
if ('source_traceback' not in context and
|
| 1736 |
+
self._current_handle is not None and
|
| 1737 |
+
self._current_handle._source_traceback):
|
| 1738 |
+
context['handle_traceback'] = \
|
| 1739 |
+
self._current_handle._source_traceback
|
| 1740 |
+
|
| 1741 |
+
log_lines = [message]
|
| 1742 |
+
for key in sorted(context):
|
| 1743 |
+
if key in {'message', 'exception'}:
|
| 1744 |
+
continue
|
| 1745 |
+
value = context[key]
|
| 1746 |
+
if key == 'source_traceback':
|
| 1747 |
+
tb = ''.join(traceback.format_list(value))
|
| 1748 |
+
value = 'Object created at (most recent call last):\n'
|
| 1749 |
+
value += tb.rstrip()
|
| 1750 |
+
elif key == 'handle_traceback':
|
| 1751 |
+
tb = ''.join(traceback.format_list(value))
|
| 1752 |
+
value = 'Handle created at (most recent call last):\n'
|
| 1753 |
+
value += tb.rstrip()
|
| 1754 |
+
else:
|
| 1755 |
+
value = repr(value)
|
| 1756 |
+
log_lines.append(f'{key}: {value}')
|
| 1757 |
+
|
| 1758 |
+
logger.error('\n'.join(log_lines), exc_info=exc_info)
|
| 1759 |
+
|
| 1760 |
+
def call_exception_handler(self, context):
|
| 1761 |
+
"""Call the current event loop's exception handler.
|
| 1762 |
+
|
| 1763 |
+
The context argument is a dict containing the following keys:
|
| 1764 |
+
|
| 1765 |
+
- 'message': Error message;
|
| 1766 |
+
- 'exception' (optional): Exception object;
|
| 1767 |
+
- 'future' (optional): Future instance;
|
| 1768 |
+
- 'task' (optional): Task instance;
|
| 1769 |
+
- 'handle' (optional): Handle instance;
|
| 1770 |
+
- 'protocol' (optional): Protocol instance;
|
| 1771 |
+
- 'transport' (optional): Transport instance;
|
| 1772 |
+
- 'socket' (optional): Socket instance;
|
| 1773 |
+
- 'asyncgen' (optional): Asynchronous generator that caused
|
| 1774 |
+
the exception.
|
| 1775 |
+
|
| 1776 |
+
New keys maybe introduced in the future.
|
| 1777 |
+
|
| 1778 |
+
Note: do not overload this method in an event loop subclass.
|
| 1779 |
+
For custom exception handling, use the
|
| 1780 |
+
`set_exception_handler()` method.
|
| 1781 |
+
"""
|
| 1782 |
+
if self._exception_handler is None:
|
| 1783 |
+
try:
|
| 1784 |
+
self.default_exception_handler(context)
|
| 1785 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1786 |
+
raise
|
| 1787 |
+
except BaseException:
|
| 1788 |
+
# Second protection layer for unexpected errors
|
| 1789 |
+
# in the default implementation, as well as for subclassed
|
| 1790 |
+
# event loops with overloaded "default_exception_handler".
|
| 1791 |
+
logger.error('Exception in default exception handler',
|
| 1792 |
+
exc_info=True)
|
| 1793 |
+
else:
|
| 1794 |
+
try:
|
| 1795 |
+
self._exception_handler(self, context)
|
| 1796 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1797 |
+
raise
|
| 1798 |
+
except BaseException as exc:
|
| 1799 |
+
# Exception in the user set custom exception handler.
|
| 1800 |
+
try:
|
| 1801 |
+
# Let's try default handler.
|
| 1802 |
+
self.default_exception_handler({
|
| 1803 |
+
'message': 'Unhandled error in exception handler',
|
| 1804 |
+
'exception': exc,
|
| 1805 |
+
'context': context,
|
| 1806 |
+
})
|
| 1807 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1808 |
+
raise
|
| 1809 |
+
except BaseException:
|
| 1810 |
+
# Guard 'default_exception_handler' in case it is
|
| 1811 |
+
# overloaded.
|
| 1812 |
+
logger.error('Exception in default exception handler '
|
| 1813 |
+
'while handling an unexpected error '
|
| 1814 |
+
'in custom exception handler',
|
| 1815 |
+
exc_info=True)
|
| 1816 |
+
|
| 1817 |
+
def _add_callback(self, handle):
|
| 1818 |
+
"""Add a Handle to _ready."""
|
| 1819 |
+
if not handle._cancelled:
|
| 1820 |
+
self._ready.append(handle)
|
| 1821 |
+
|
| 1822 |
+
def _add_callback_signalsafe(self, handle):
|
| 1823 |
+
"""Like _add_callback() but called from a signal handler."""
|
| 1824 |
+
self._add_callback(handle)
|
| 1825 |
+
self._write_to_self()
|
| 1826 |
+
|
| 1827 |
+
def _timer_handle_cancelled(self, handle):
|
| 1828 |
+
"""Notification that a TimerHandle has been cancelled."""
|
| 1829 |
+
if handle._scheduled:
|
| 1830 |
+
self._timer_cancelled_count += 1
|
| 1831 |
+
|
| 1832 |
+
def _run_once(self):
|
| 1833 |
+
"""Run one full iteration of the event loop.
|
| 1834 |
+
|
| 1835 |
+
This calls all currently ready callbacks, polls for I/O,
|
| 1836 |
+
schedules the resulting callbacks, and finally schedules
|
| 1837 |
+
'call_later' callbacks.
|
| 1838 |
+
"""
|
| 1839 |
+
|
| 1840 |
+
sched_count = len(self._scheduled)
|
| 1841 |
+
if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
|
| 1842 |
+
self._timer_cancelled_count / sched_count >
|
| 1843 |
+
_MIN_CANCELLED_TIMER_HANDLES_FRACTION):
|
| 1844 |
+
# Remove delayed calls that were cancelled if their number
|
| 1845 |
+
# is too high
|
| 1846 |
+
new_scheduled = []
|
| 1847 |
+
for handle in self._scheduled:
|
| 1848 |
+
if handle._cancelled:
|
| 1849 |
+
handle._scheduled = False
|
| 1850 |
+
else:
|
| 1851 |
+
new_scheduled.append(handle)
|
| 1852 |
+
|
| 1853 |
+
heapq.heapify(new_scheduled)
|
| 1854 |
+
self._scheduled = new_scheduled
|
| 1855 |
+
self._timer_cancelled_count = 0
|
| 1856 |
+
else:
|
| 1857 |
+
# Remove delayed calls that were cancelled from head of queue.
|
| 1858 |
+
while self._scheduled and self._scheduled[0]._cancelled:
|
| 1859 |
+
self._timer_cancelled_count -= 1
|
| 1860 |
+
handle = heapq.heappop(self._scheduled)
|
| 1861 |
+
handle._scheduled = False
|
| 1862 |
+
|
| 1863 |
+
timeout = None
|
| 1864 |
+
if self._ready or self._stopping:
|
| 1865 |
+
timeout = 0
|
| 1866 |
+
elif self._scheduled:
|
| 1867 |
+
# Compute the desired timeout.
|
| 1868 |
+
when = self._scheduled[0]._when
|
| 1869 |
+
timeout = min(max(0, when - self.time()), MAXIMUM_SELECT_TIMEOUT)
|
| 1870 |
+
|
| 1871 |
+
event_list = self._selector.select(timeout)
|
| 1872 |
+
self._process_events(event_list)
|
| 1873 |
+
# Needed to break cycles when an exception occurs.
|
| 1874 |
+
event_list = None
|
| 1875 |
+
|
| 1876 |
+
# Handle 'later' callbacks that are ready.
|
| 1877 |
+
end_time = self.time() + self._clock_resolution
|
| 1878 |
+
while self._scheduled:
|
| 1879 |
+
handle = self._scheduled[0]
|
| 1880 |
+
if handle._when >= end_time:
|
| 1881 |
+
break
|
| 1882 |
+
handle = heapq.heappop(self._scheduled)
|
| 1883 |
+
handle._scheduled = False
|
| 1884 |
+
self._ready.append(handle)
|
| 1885 |
+
|
| 1886 |
+
# This is the only place where callbacks are actually *called*.
|
| 1887 |
+
# All other places just add them to ready.
|
| 1888 |
+
# Note: We run all currently scheduled callbacks, but not any
|
| 1889 |
+
# callbacks scheduled by callbacks run this time around --
|
| 1890 |
+
# they will be run the next time (after another I/O poll).
|
| 1891 |
+
# Use an idiom that is thread-safe without using locks.
|
| 1892 |
+
ntodo = len(self._ready)
|
| 1893 |
+
for i in range(ntodo):
|
| 1894 |
+
handle = self._ready.popleft()
|
| 1895 |
+
if handle._cancelled:
|
| 1896 |
+
continue
|
| 1897 |
+
if self._debug:
|
| 1898 |
+
try:
|
| 1899 |
+
self._current_handle = handle
|
| 1900 |
+
t0 = self.time()
|
| 1901 |
+
handle._run()
|
| 1902 |
+
dt = self.time() - t0
|
| 1903 |
+
if dt >= self.slow_callback_duration:
|
| 1904 |
+
logger.warning('Executing %s took %.3f seconds',
|
| 1905 |
+
_format_handle(handle), dt)
|
| 1906 |
+
finally:
|
| 1907 |
+
self._current_handle = None
|
| 1908 |
+
else:
|
| 1909 |
+
handle._run()
|
| 1910 |
+
handle = None # Needed to break cycles when an exception occurs.
|
| 1911 |
+
|
| 1912 |
+
def _set_coroutine_origin_tracking(self, enabled):
|
| 1913 |
+
if bool(enabled) == bool(self._coroutine_origin_tracking_enabled):
|
| 1914 |
+
return
|
| 1915 |
+
|
| 1916 |
+
if enabled:
|
| 1917 |
+
self._coroutine_origin_tracking_saved_depth = (
|
| 1918 |
+
sys.get_coroutine_origin_tracking_depth())
|
| 1919 |
+
sys.set_coroutine_origin_tracking_depth(
|
| 1920 |
+
constants.DEBUG_STACK_DEPTH)
|
| 1921 |
+
else:
|
| 1922 |
+
sys.set_coroutine_origin_tracking_depth(
|
| 1923 |
+
self._coroutine_origin_tracking_saved_depth)
|
| 1924 |
+
|
| 1925 |
+
self._coroutine_origin_tracking_enabled = enabled
|
| 1926 |
+
|
| 1927 |
+
def get_debug(self):
|
| 1928 |
+
return self._debug
|
| 1929 |
+
|
| 1930 |
+
def set_debug(self, enabled):
|
| 1931 |
+
self._debug = enabled
|
| 1932 |
+
|
| 1933 |
+
if self.is_running():
|
| 1934 |
+
self.call_soon_threadsafe(self._set_coroutine_origin_tracking, enabled)
|
janus/lib/python3.10/asyncio/base_tasks.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import linecache
|
| 2 |
+
import traceback
|
| 3 |
+
|
| 4 |
+
from . import base_futures
|
| 5 |
+
from . import coroutines
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _task_repr_info(task):
|
| 9 |
+
info = base_futures._future_repr_info(task)
|
| 10 |
+
|
| 11 |
+
if task._must_cancel:
|
| 12 |
+
# replace status
|
| 13 |
+
info[0] = 'cancelling'
|
| 14 |
+
|
| 15 |
+
info.insert(1, 'name=%r' % task.get_name())
|
| 16 |
+
|
| 17 |
+
coro = coroutines._format_coroutine(task._coro)
|
| 18 |
+
info.insert(2, f'coro=<{coro}>')
|
| 19 |
+
|
| 20 |
+
if task._fut_waiter is not None:
|
| 21 |
+
info.insert(3, f'wait_for={task._fut_waiter!r}')
|
| 22 |
+
return info
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _task_get_stack(task, limit):
|
| 26 |
+
frames = []
|
| 27 |
+
if hasattr(task._coro, 'cr_frame'):
|
| 28 |
+
# case 1: 'async def' coroutines
|
| 29 |
+
f = task._coro.cr_frame
|
| 30 |
+
elif hasattr(task._coro, 'gi_frame'):
|
| 31 |
+
# case 2: legacy coroutines
|
| 32 |
+
f = task._coro.gi_frame
|
| 33 |
+
elif hasattr(task._coro, 'ag_frame'):
|
| 34 |
+
# case 3: async generators
|
| 35 |
+
f = task._coro.ag_frame
|
| 36 |
+
else:
|
| 37 |
+
# case 4: unknown objects
|
| 38 |
+
f = None
|
| 39 |
+
if f is not None:
|
| 40 |
+
while f is not None:
|
| 41 |
+
if limit is not None:
|
| 42 |
+
if limit <= 0:
|
| 43 |
+
break
|
| 44 |
+
limit -= 1
|
| 45 |
+
frames.append(f)
|
| 46 |
+
f = f.f_back
|
| 47 |
+
frames.reverse()
|
| 48 |
+
elif task._exception is not None:
|
| 49 |
+
tb = task._exception.__traceback__
|
| 50 |
+
while tb is not None:
|
| 51 |
+
if limit is not None:
|
| 52 |
+
if limit <= 0:
|
| 53 |
+
break
|
| 54 |
+
limit -= 1
|
| 55 |
+
frames.append(tb.tb_frame)
|
| 56 |
+
tb = tb.tb_next
|
| 57 |
+
return frames
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _task_print_stack(task, limit, file):
|
| 61 |
+
extracted_list = []
|
| 62 |
+
checked = set()
|
| 63 |
+
for f in task.get_stack(limit=limit):
|
| 64 |
+
lineno = f.f_lineno
|
| 65 |
+
co = f.f_code
|
| 66 |
+
filename = co.co_filename
|
| 67 |
+
name = co.co_name
|
| 68 |
+
if filename not in checked:
|
| 69 |
+
checked.add(filename)
|
| 70 |
+
linecache.checkcache(filename)
|
| 71 |
+
line = linecache.getline(filename, lineno, f.f_globals)
|
| 72 |
+
extracted_list.append((filename, lineno, name, line))
|
| 73 |
+
|
| 74 |
+
exc = task._exception
|
| 75 |
+
if not extracted_list:
|
| 76 |
+
print(f'No stack for {task!r}', file=file)
|
| 77 |
+
elif exc is not None:
|
| 78 |
+
print(f'Traceback for {task!r} (most recent call last):', file=file)
|
| 79 |
+
else:
|
| 80 |
+
print(f'Stack for {task!r} (most recent call last):', file=file)
|
| 81 |
+
|
| 82 |
+
traceback.print_list(extracted_list, file=file)
|
| 83 |
+
if exc is not None:
|
| 84 |
+
for line in traceback.format_exception_only(exc.__class__, exc):
|
| 85 |
+
print(line, file=file, end='')
|
janus/lib/python3.10/asyncio/coroutines.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__all__ = 'coroutine', 'iscoroutinefunction', 'iscoroutine'
|
| 2 |
+
|
| 3 |
+
import collections.abc
|
| 4 |
+
import functools
|
| 5 |
+
import inspect
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
import traceback
|
| 9 |
+
import types
|
| 10 |
+
import warnings
|
| 11 |
+
|
| 12 |
+
from . import base_futures
|
| 13 |
+
from . import constants
|
| 14 |
+
from . import format_helpers
|
| 15 |
+
from .log import logger
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _is_debug_mode():
|
| 19 |
+
# If you set _DEBUG to true, @coroutine will wrap the resulting
|
| 20 |
+
# generator objects in a CoroWrapper instance (defined below). That
|
| 21 |
+
# instance will log a message when the generator is never iterated
|
| 22 |
+
# over, which may happen when you forget to use "await" or "yield from"
|
| 23 |
+
# with a coroutine call.
|
| 24 |
+
# Note that the value of the _DEBUG flag is taken
|
| 25 |
+
# when the decorator is used, so to be of any use it must be set
|
| 26 |
+
# before you define your coroutines. A downside of using this feature
|
| 27 |
+
# is that tracebacks show entries for the CoroWrapper.__next__ method
|
| 28 |
+
# when _DEBUG is true.
|
| 29 |
+
return sys.flags.dev_mode or (not sys.flags.ignore_environment and
|
| 30 |
+
bool(os.environ.get('PYTHONASYNCIODEBUG')))
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
_DEBUG = _is_debug_mode()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class CoroWrapper:
|
| 37 |
+
# Wrapper for coroutine object in _DEBUG mode.
|
| 38 |
+
|
| 39 |
+
def __init__(self, gen, func=None):
|
| 40 |
+
assert inspect.isgenerator(gen) or inspect.iscoroutine(gen), gen
|
| 41 |
+
self.gen = gen
|
| 42 |
+
self.func = func # Used to unwrap @coroutine decorator
|
| 43 |
+
self._source_traceback = format_helpers.extract_stack(sys._getframe(1))
|
| 44 |
+
self.__name__ = getattr(gen, '__name__', None)
|
| 45 |
+
self.__qualname__ = getattr(gen, '__qualname__', None)
|
| 46 |
+
|
| 47 |
+
def __repr__(self):
|
| 48 |
+
coro_repr = _format_coroutine(self)
|
| 49 |
+
if self._source_traceback:
|
| 50 |
+
frame = self._source_traceback[-1]
|
| 51 |
+
coro_repr += f', created at {frame[0]}:{frame[1]}'
|
| 52 |
+
|
| 53 |
+
return f'<{self.__class__.__name__} {coro_repr}>'
|
| 54 |
+
|
| 55 |
+
def __iter__(self):
|
| 56 |
+
return self
|
| 57 |
+
|
| 58 |
+
def __next__(self):
|
| 59 |
+
return self.gen.send(None)
|
| 60 |
+
|
| 61 |
+
def send(self, value):
|
| 62 |
+
return self.gen.send(value)
|
| 63 |
+
|
| 64 |
+
def throw(self, type, value=None, traceback=None):
|
| 65 |
+
return self.gen.throw(type, value, traceback)
|
| 66 |
+
|
| 67 |
+
def close(self):
|
| 68 |
+
return self.gen.close()
|
| 69 |
+
|
| 70 |
+
@property
|
| 71 |
+
def gi_frame(self):
|
| 72 |
+
return self.gen.gi_frame
|
| 73 |
+
|
| 74 |
+
@property
|
| 75 |
+
def gi_running(self):
|
| 76 |
+
return self.gen.gi_running
|
| 77 |
+
|
| 78 |
+
@property
|
| 79 |
+
def gi_code(self):
|
| 80 |
+
return self.gen.gi_code
|
| 81 |
+
|
| 82 |
+
def __await__(self):
|
| 83 |
+
return self
|
| 84 |
+
|
| 85 |
+
@property
|
| 86 |
+
def gi_yieldfrom(self):
|
| 87 |
+
return self.gen.gi_yieldfrom
|
| 88 |
+
|
| 89 |
+
def __del__(self):
|
| 90 |
+
# Be careful accessing self.gen.frame -- self.gen might not exist.
|
| 91 |
+
gen = getattr(self, 'gen', None)
|
| 92 |
+
frame = getattr(gen, 'gi_frame', None)
|
| 93 |
+
if frame is not None and frame.f_lasti == -1:
|
| 94 |
+
msg = f'{self!r} was never yielded from'
|
| 95 |
+
tb = getattr(self, '_source_traceback', ())
|
| 96 |
+
if tb:
|
| 97 |
+
tb = ''.join(traceback.format_list(tb))
|
| 98 |
+
msg += (f'\nCoroutine object created at '
|
| 99 |
+
f'(most recent call last, truncated to '
|
| 100 |
+
f'{constants.DEBUG_STACK_DEPTH} last lines):\n')
|
| 101 |
+
msg += tb.rstrip()
|
| 102 |
+
logger.error(msg)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def coroutine(func):
|
| 106 |
+
"""Decorator to mark coroutines.
|
| 107 |
+
|
| 108 |
+
If the coroutine is not yielded from before it is destroyed,
|
| 109 |
+
an error message is logged.
|
| 110 |
+
"""
|
| 111 |
+
warnings.warn('"@coroutine" decorator is deprecated since Python 3.8, use "async def" instead',
|
| 112 |
+
DeprecationWarning,
|
| 113 |
+
stacklevel=2)
|
| 114 |
+
if inspect.iscoroutinefunction(func):
|
| 115 |
+
# In Python 3.5 that's all we need to do for coroutines
|
| 116 |
+
# defined with "async def".
|
| 117 |
+
return func
|
| 118 |
+
|
| 119 |
+
if inspect.isgeneratorfunction(func):
|
| 120 |
+
coro = func
|
| 121 |
+
else:
|
| 122 |
+
@functools.wraps(func)
|
| 123 |
+
def coro(*args, **kw):
|
| 124 |
+
res = func(*args, **kw)
|
| 125 |
+
if (base_futures.isfuture(res) or inspect.isgenerator(res) or
|
| 126 |
+
isinstance(res, CoroWrapper)):
|
| 127 |
+
res = yield from res
|
| 128 |
+
else:
|
| 129 |
+
# If 'res' is an awaitable, run it.
|
| 130 |
+
try:
|
| 131 |
+
await_meth = res.__await__
|
| 132 |
+
except AttributeError:
|
| 133 |
+
pass
|
| 134 |
+
else:
|
| 135 |
+
if isinstance(res, collections.abc.Awaitable):
|
| 136 |
+
res = yield from await_meth()
|
| 137 |
+
return res
|
| 138 |
+
|
| 139 |
+
coro = types.coroutine(coro)
|
| 140 |
+
if not _DEBUG:
|
| 141 |
+
wrapper = coro
|
| 142 |
+
else:
|
| 143 |
+
@functools.wraps(func)
|
| 144 |
+
def wrapper(*args, **kwds):
|
| 145 |
+
w = CoroWrapper(coro(*args, **kwds), func=func)
|
| 146 |
+
if w._source_traceback:
|
| 147 |
+
del w._source_traceback[-1]
|
| 148 |
+
# Python < 3.5 does not implement __qualname__
|
| 149 |
+
# on generator objects, so we set it manually.
|
| 150 |
+
# We use getattr as some callables (such as
|
| 151 |
+
# functools.partial may lack __qualname__).
|
| 152 |
+
w.__name__ = getattr(func, '__name__', None)
|
| 153 |
+
w.__qualname__ = getattr(func, '__qualname__', None)
|
| 154 |
+
return w
|
| 155 |
+
|
| 156 |
+
wrapper._is_coroutine = _is_coroutine # For iscoroutinefunction().
|
| 157 |
+
return wrapper
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
# A marker for iscoroutinefunction.
|
| 161 |
+
_is_coroutine = object()
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def iscoroutinefunction(func):
|
| 165 |
+
"""Return True if func is a decorated coroutine function."""
|
| 166 |
+
return (inspect.iscoroutinefunction(func) or
|
| 167 |
+
getattr(func, '_is_coroutine', None) is _is_coroutine)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
# Prioritize native coroutine check to speed-up
|
| 171 |
+
# asyncio.iscoroutine.
|
| 172 |
+
_COROUTINE_TYPES = (types.CoroutineType, types.GeneratorType,
|
| 173 |
+
collections.abc.Coroutine, CoroWrapper)
|
| 174 |
+
_iscoroutine_typecache = set()
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def iscoroutine(obj):
|
| 178 |
+
"""Return True if obj is a coroutine object."""
|
| 179 |
+
if type(obj) in _iscoroutine_typecache:
|
| 180 |
+
return True
|
| 181 |
+
|
| 182 |
+
if isinstance(obj, _COROUTINE_TYPES):
|
| 183 |
+
# Just in case we don't want to cache more than 100
|
| 184 |
+
# positive types. That shouldn't ever happen, unless
|
| 185 |
+
# someone stressing the system on purpose.
|
| 186 |
+
if len(_iscoroutine_typecache) < 100:
|
| 187 |
+
_iscoroutine_typecache.add(type(obj))
|
| 188 |
+
return True
|
| 189 |
+
else:
|
| 190 |
+
return False
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def _format_coroutine(coro):
|
| 194 |
+
assert iscoroutine(coro)
|
| 195 |
+
|
| 196 |
+
is_corowrapper = isinstance(coro, CoroWrapper)
|
| 197 |
+
|
| 198 |
+
def get_name(coro):
|
| 199 |
+
# Coroutines compiled with Cython sometimes don't have
|
| 200 |
+
# proper __qualname__ or __name__. While that is a bug
|
| 201 |
+
# in Cython, asyncio shouldn't crash with an AttributeError
|
| 202 |
+
# in its __repr__ functions.
|
| 203 |
+
if is_corowrapper:
|
| 204 |
+
return format_helpers._format_callback(coro.func, (), {})
|
| 205 |
+
|
| 206 |
+
if hasattr(coro, '__qualname__') and coro.__qualname__:
|
| 207 |
+
coro_name = coro.__qualname__
|
| 208 |
+
elif hasattr(coro, '__name__') and coro.__name__:
|
| 209 |
+
coro_name = coro.__name__
|
| 210 |
+
else:
|
| 211 |
+
# Stop masking Cython bugs, expose them in a friendly way.
|
| 212 |
+
coro_name = f'<{type(coro).__name__} without __name__>'
|
| 213 |
+
return f'{coro_name}()'
|
| 214 |
+
|
| 215 |
+
def is_running(coro):
|
| 216 |
+
try:
|
| 217 |
+
return coro.cr_running
|
| 218 |
+
except AttributeError:
|
| 219 |
+
try:
|
| 220 |
+
return coro.gi_running
|
| 221 |
+
except AttributeError:
|
| 222 |
+
return False
|
| 223 |
+
|
| 224 |
+
coro_code = None
|
| 225 |
+
if hasattr(coro, 'cr_code') and coro.cr_code:
|
| 226 |
+
coro_code = coro.cr_code
|
| 227 |
+
elif hasattr(coro, 'gi_code') and coro.gi_code:
|
| 228 |
+
coro_code = coro.gi_code
|
| 229 |
+
|
| 230 |
+
coro_name = get_name(coro)
|
| 231 |
+
|
| 232 |
+
if not coro_code:
|
| 233 |
+
# Built-in types might not have __qualname__ or __name__.
|
| 234 |
+
if is_running(coro):
|
| 235 |
+
return f'{coro_name} running'
|
| 236 |
+
else:
|
| 237 |
+
return coro_name
|
| 238 |
+
|
| 239 |
+
coro_frame = None
|
| 240 |
+
if hasattr(coro, 'gi_frame') and coro.gi_frame:
|
| 241 |
+
coro_frame = coro.gi_frame
|
| 242 |
+
elif hasattr(coro, 'cr_frame') and coro.cr_frame:
|
| 243 |
+
coro_frame = coro.cr_frame
|
| 244 |
+
|
| 245 |
+
# If Cython's coroutine has a fake code object without proper
|
| 246 |
+
# co_filename -- expose that.
|
| 247 |
+
filename = coro_code.co_filename or '<empty co_filename>'
|
| 248 |
+
|
| 249 |
+
lineno = 0
|
| 250 |
+
if (is_corowrapper and
|
| 251 |
+
coro.func is not None and
|
| 252 |
+
not inspect.isgeneratorfunction(coro.func)):
|
| 253 |
+
source = format_helpers._get_function_source(coro.func)
|
| 254 |
+
if source is not None:
|
| 255 |
+
filename, lineno = source
|
| 256 |
+
if coro_frame is None:
|
| 257 |
+
coro_repr = f'{coro_name} done, defined at {filename}:{lineno}'
|
| 258 |
+
else:
|
| 259 |
+
coro_repr = f'{coro_name} running, defined at {filename}:{lineno}'
|
| 260 |
+
|
| 261 |
+
elif coro_frame is not None:
|
| 262 |
+
lineno = coro_frame.f_lineno
|
| 263 |
+
coro_repr = f'{coro_name} running at {filename}:{lineno}'
|
| 264 |
+
|
| 265 |
+
else:
|
| 266 |
+
lineno = coro_code.co_firstlineno
|
| 267 |
+
coro_repr = f'{coro_name} done, defined at {filename}:{lineno}'
|
| 268 |
+
|
| 269 |
+
return coro_repr
|
janus/lib/python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policy',
|
| 8 |
+
'get_event_loop', 'set_event_loop', 'new_event_loop',
|
| 9 |
+
'get_child_watcher', 'set_child_watcher',
|
| 10 |
+
'_set_running_loop', 'get_running_loop',
|
| 11 |
+
'_get_running_loop',
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
import contextvars
|
| 15 |
+
import os
|
| 16 |
+
import socket
|
| 17 |
+
import subprocess
|
| 18 |
+
import sys
|
| 19 |
+
import threading
|
| 20 |
+
|
| 21 |
+
from . import format_helpers
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Handle:
|
| 25 |
+
"""Object returned by callback registration methods."""
|
| 26 |
+
|
| 27 |
+
__slots__ = ('_callback', '_args', '_cancelled', '_loop',
|
| 28 |
+
'_source_traceback', '_repr', '__weakref__',
|
| 29 |
+
'_context')
|
| 30 |
+
|
| 31 |
+
def __init__(self, callback, args, loop, context=None):
|
| 32 |
+
if context is None:
|
| 33 |
+
context = contextvars.copy_context()
|
| 34 |
+
self._context = context
|
| 35 |
+
self._loop = loop
|
| 36 |
+
self._callback = callback
|
| 37 |
+
self._args = args
|
| 38 |
+
self._cancelled = False
|
| 39 |
+
self._repr = None
|
| 40 |
+
if self._loop.get_debug():
|
| 41 |
+
self._source_traceback = format_helpers.extract_stack(
|
| 42 |
+
sys._getframe(1))
|
| 43 |
+
else:
|
| 44 |
+
self._source_traceback = None
|
| 45 |
+
|
| 46 |
+
def _repr_info(self):
|
| 47 |
+
info = [self.__class__.__name__]
|
| 48 |
+
if self._cancelled:
|
| 49 |
+
info.append('cancelled')
|
| 50 |
+
if self._callback is not None:
|
| 51 |
+
info.append(format_helpers._format_callback_source(
|
| 52 |
+
self._callback, self._args))
|
| 53 |
+
if self._source_traceback:
|
| 54 |
+
frame = self._source_traceback[-1]
|
| 55 |
+
info.append(f'created at {frame[0]}:{frame[1]}')
|
| 56 |
+
return info
|
| 57 |
+
|
| 58 |
+
def __repr__(self):
|
| 59 |
+
if self._repr is not None:
|
| 60 |
+
return self._repr
|
| 61 |
+
info = self._repr_info()
|
| 62 |
+
return '<{}>'.format(' '.join(info))
|
| 63 |
+
|
| 64 |
+
def cancel(self):
|
| 65 |
+
if not self._cancelled:
|
| 66 |
+
self._cancelled = True
|
| 67 |
+
if self._loop.get_debug():
|
| 68 |
+
# Keep a representation in debug mode to keep callback and
|
| 69 |
+
# parameters. For example, to log the warning
|
| 70 |
+
# "Executing <Handle...> took 2.5 second"
|
| 71 |
+
self._repr = repr(self)
|
| 72 |
+
self._callback = None
|
| 73 |
+
self._args = None
|
| 74 |
+
|
| 75 |
+
def cancelled(self):
|
| 76 |
+
return self._cancelled
|
| 77 |
+
|
| 78 |
+
def _run(self):
|
| 79 |
+
try:
|
| 80 |
+
self._context.run(self._callback, *self._args)
|
| 81 |
+
except (SystemExit, KeyboardInterrupt):
|
| 82 |
+
raise
|
| 83 |
+
except BaseException as exc:
|
| 84 |
+
cb = format_helpers._format_callback_source(
|
| 85 |
+
self._callback, self._args)
|
| 86 |
+
msg = f'Exception in callback {cb}'
|
| 87 |
+
context = {
|
| 88 |
+
'message': msg,
|
| 89 |
+
'exception': exc,
|
| 90 |
+
'handle': self,
|
| 91 |
+
}
|
| 92 |
+
if self._source_traceback:
|
| 93 |
+
context['source_traceback'] = self._source_traceback
|
| 94 |
+
self._loop.call_exception_handler(context)
|
| 95 |
+
self = None # Needed to break cycles when an exception occurs.
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class TimerHandle(Handle):
|
| 99 |
+
"""Object returned by timed callback registration methods."""
|
| 100 |
+
|
| 101 |
+
__slots__ = ['_scheduled', '_when']
|
| 102 |
+
|
| 103 |
+
def __init__(self, when, callback, args, loop, context=None):
|
| 104 |
+
assert when is not None
|
| 105 |
+
super().__init__(callback, args, loop, context)
|
| 106 |
+
if self._source_traceback:
|
| 107 |
+
del self._source_traceback[-1]
|
| 108 |
+
self._when = when
|
| 109 |
+
self._scheduled = False
|
| 110 |
+
|
| 111 |
+
def _repr_info(self):
|
| 112 |
+
info = super()._repr_info()
|
| 113 |
+
pos = 2 if self._cancelled else 1
|
| 114 |
+
info.insert(pos, f'when={self._when}')
|
| 115 |
+
return info
|
| 116 |
+
|
| 117 |
+
def __hash__(self):
|
| 118 |
+
return hash(self._when)
|
| 119 |
+
|
| 120 |
+
def __lt__(self, other):
|
| 121 |
+
if isinstance(other, TimerHandle):
|
| 122 |
+
return self._when < other._when
|
| 123 |
+
return NotImplemented
|
| 124 |
+
|
| 125 |
+
def __le__(self, other):
|
| 126 |
+
if isinstance(other, TimerHandle):
|
| 127 |
+
return self._when < other._when or self.__eq__(other)
|
| 128 |
+
return NotImplemented
|
| 129 |
+
|
| 130 |
+
def __gt__(self, other):
|
| 131 |
+
if isinstance(other, TimerHandle):
|
| 132 |
+
return self._when > other._when
|
| 133 |
+
return NotImplemented
|
| 134 |
+
|
| 135 |
+
def __ge__(self, other):
|
| 136 |
+
if isinstance(other, TimerHandle):
|
| 137 |
+
return self._when > other._when or self.__eq__(other)
|
| 138 |
+
return NotImplemented
|
| 139 |
+
|
| 140 |
+
def __eq__(self, other):
|
| 141 |
+
if isinstance(other, TimerHandle):
|
| 142 |
+
return (self._when == other._when and
|
| 143 |
+
self._callback == other._callback and
|
| 144 |
+
self._args == other._args and
|
| 145 |
+
self._cancelled == other._cancelled)
|
| 146 |
+
return NotImplemented
|
| 147 |
+
|
| 148 |
+
def cancel(self):
|
| 149 |
+
if not self._cancelled:
|
| 150 |
+
self._loop._timer_handle_cancelled(self)
|
| 151 |
+
super().cancel()
|
| 152 |
+
|
| 153 |
+
def when(self):
|
| 154 |
+
"""Return a scheduled callback time.
|
| 155 |
+
|
| 156 |
+
The time is an absolute timestamp, using the same time
|
| 157 |
+
reference as loop.time().
|
| 158 |
+
"""
|
| 159 |
+
return self._when
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class AbstractServer:
|
| 163 |
+
"""Abstract server returned by create_server()."""
|
| 164 |
+
|
| 165 |
+
def close(self):
|
| 166 |
+
"""Stop serving. This leaves existing connections open."""
|
| 167 |
+
raise NotImplementedError
|
| 168 |
+
|
| 169 |
+
def get_loop(self):
|
| 170 |
+
"""Get the event loop the Server object is attached to."""
|
| 171 |
+
raise NotImplementedError
|
| 172 |
+
|
| 173 |
+
def is_serving(self):
|
| 174 |
+
"""Return True if the server is accepting connections."""
|
| 175 |
+
raise NotImplementedError
|
| 176 |
+
|
| 177 |
+
async def start_serving(self):
|
| 178 |
+
"""Start accepting connections.
|
| 179 |
+
|
| 180 |
+
This method is idempotent, so it can be called when
|
| 181 |
+
the server is already being serving.
|
| 182 |
+
"""
|
| 183 |
+
raise NotImplementedError
|
| 184 |
+
|
| 185 |
+
async def serve_forever(self):
|
| 186 |
+
"""Start accepting connections until the coroutine is cancelled.
|
| 187 |
+
|
| 188 |
+
The server is closed when the coroutine is cancelled.
|
| 189 |
+
"""
|
| 190 |
+
raise NotImplementedError
|
| 191 |
+
|
| 192 |
+
async def wait_closed(self):
|
| 193 |
+
"""Coroutine to wait until service is closed."""
|
| 194 |
+
raise NotImplementedError
|
| 195 |
+
|
| 196 |
+
async def __aenter__(self):
|
| 197 |
+
return self
|
| 198 |
+
|
| 199 |
+
async def __aexit__(self, *exc):
|
| 200 |
+
self.close()
|
| 201 |
+
await self.wait_closed()
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class AbstractEventLoop:
|
| 205 |
+
"""Abstract event loop."""
|
| 206 |
+
|
| 207 |
+
# Running and stopping the event loop.
|
| 208 |
+
|
| 209 |
+
def run_forever(self):
|
| 210 |
+
"""Run the event loop until stop() is called."""
|
| 211 |
+
raise NotImplementedError
|
| 212 |
+
|
| 213 |
+
def run_until_complete(self, future):
|
| 214 |
+
"""Run the event loop until a Future is done.
|
| 215 |
+
|
| 216 |
+
Return the Future's result, or raise its exception.
|
| 217 |
+
"""
|
| 218 |
+
raise NotImplementedError
|
| 219 |
+
|
| 220 |
+
def stop(self):
|
| 221 |
+
"""Stop the event loop as soon as reasonable.
|
| 222 |
+
|
| 223 |
+
Exactly how soon that is may depend on the implementation, but
|
| 224 |
+
no more I/O callbacks should be scheduled.
|
| 225 |
+
"""
|
| 226 |
+
raise NotImplementedError
|
| 227 |
+
|
| 228 |
+
def is_running(self):
|
| 229 |
+
"""Return whether the event loop is currently running."""
|
| 230 |
+
raise NotImplementedError
|
| 231 |
+
|
| 232 |
+
def is_closed(self):
|
| 233 |
+
"""Returns True if the event loop was closed."""
|
| 234 |
+
raise NotImplementedError
|
| 235 |
+
|
| 236 |
+
def close(self):
|
| 237 |
+
"""Close the loop.
|
| 238 |
+
|
| 239 |
+
The loop should not be running.
|
| 240 |
+
|
| 241 |
+
This is idempotent and irreversible.
|
| 242 |
+
|
| 243 |
+
No other methods should be called after this one.
|
| 244 |
+
"""
|
| 245 |
+
raise NotImplementedError
|
| 246 |
+
|
| 247 |
+
async def shutdown_asyncgens(self):
|
| 248 |
+
"""Shutdown all active asynchronous generators."""
|
| 249 |
+
raise NotImplementedError
|
| 250 |
+
|
| 251 |
+
async def shutdown_default_executor(self):
|
| 252 |
+
"""Schedule the shutdown of the default executor."""
|
| 253 |
+
raise NotImplementedError
|
| 254 |
+
|
| 255 |
+
# Methods scheduling callbacks. All these return Handles.
|
| 256 |
+
|
| 257 |
+
def _timer_handle_cancelled(self, handle):
|
| 258 |
+
"""Notification that a TimerHandle has been cancelled."""
|
| 259 |
+
raise NotImplementedError
|
| 260 |
+
|
| 261 |
+
def call_soon(self, callback, *args, context=None):
|
| 262 |
+
return self.call_later(0, callback, *args, context=context)
|
| 263 |
+
|
| 264 |
+
def call_later(self, delay, callback, *args, context=None):
|
| 265 |
+
raise NotImplementedError
|
| 266 |
+
|
| 267 |
+
def call_at(self, when, callback, *args, context=None):
|
| 268 |
+
raise NotImplementedError
|
| 269 |
+
|
| 270 |
+
def time(self):
|
| 271 |
+
raise NotImplementedError
|
| 272 |
+
|
| 273 |
+
def create_future(self):
|
| 274 |
+
raise NotImplementedError
|
| 275 |
+
|
| 276 |
+
# Method scheduling a coroutine object: create a task.
|
| 277 |
+
|
| 278 |
+
def create_task(self, coro, *, name=None):
|
| 279 |
+
raise NotImplementedError
|
| 280 |
+
|
| 281 |
+
# Methods for interacting with threads.
|
| 282 |
+
|
| 283 |
+
def call_soon_threadsafe(self, callback, *args, context=None):
|
| 284 |
+
raise NotImplementedError
|
| 285 |
+
|
| 286 |
+
def run_in_executor(self, executor, func, *args):
|
| 287 |
+
raise NotImplementedError
|
| 288 |
+
|
| 289 |
+
def set_default_executor(self, executor):
|
| 290 |
+
raise NotImplementedError
|
| 291 |
+
|
| 292 |
+
# Network I/O methods returning Futures.
|
| 293 |
+
|
| 294 |
+
async def getaddrinfo(self, host, port, *,
|
| 295 |
+
family=0, type=0, proto=0, flags=0):
|
| 296 |
+
raise NotImplementedError
|
| 297 |
+
|
| 298 |
+
async def getnameinfo(self, sockaddr, flags=0):
|
| 299 |
+
raise NotImplementedError
|
| 300 |
+
|
| 301 |
+
async def create_connection(
|
| 302 |
+
self, protocol_factory, host=None, port=None,
|
| 303 |
+
*, ssl=None, family=0, proto=0,
|
| 304 |
+
flags=0, sock=None, local_addr=None,
|
| 305 |
+
server_hostname=None,
|
| 306 |
+
ssl_handshake_timeout=None,
|
| 307 |
+
happy_eyeballs_delay=None, interleave=None):
|
| 308 |
+
raise NotImplementedError
|
| 309 |
+
|
| 310 |
+
async def create_server(
|
| 311 |
+
self, protocol_factory, host=None, port=None,
|
| 312 |
+
*, family=socket.AF_UNSPEC,
|
| 313 |
+
flags=socket.AI_PASSIVE, sock=None, backlog=100,
|
| 314 |
+
ssl=None, reuse_address=None, reuse_port=None,
|
| 315 |
+
ssl_handshake_timeout=None,
|
| 316 |
+
start_serving=True):
|
| 317 |
+
"""A coroutine which creates a TCP server bound to host and port.
|
| 318 |
+
|
| 319 |
+
The return value is a Server object which can be used to stop
|
| 320 |
+
the service.
|
| 321 |
+
|
| 322 |
+
If host is an empty string or None all interfaces are assumed
|
| 323 |
+
and a list of multiple sockets will be returned (most likely
|
| 324 |
+
one for IPv4 and another one for IPv6). The host parameter can also be
|
| 325 |
+
a sequence (e.g. list) of hosts to bind to.
|
| 326 |
+
|
| 327 |
+
family can be set to either AF_INET or AF_INET6 to force the
|
| 328 |
+
socket to use IPv4 or IPv6. If not set it will be determined
|
| 329 |
+
from host (defaults to AF_UNSPEC).
|
| 330 |
+
|
| 331 |
+
flags is a bitmask for getaddrinfo().
|
| 332 |
+
|
| 333 |
+
sock can optionally be specified in order to use a preexisting
|
| 334 |
+
socket object.
|
| 335 |
+
|
| 336 |
+
backlog is the maximum number of queued connections passed to
|
| 337 |
+
listen() (defaults to 100).
|
| 338 |
+
|
| 339 |
+
ssl can be set to an SSLContext to enable SSL over the
|
| 340 |
+
accepted connections.
|
| 341 |
+
|
| 342 |
+
reuse_address tells the kernel to reuse a local socket in
|
| 343 |
+
TIME_WAIT state, without waiting for its natural timeout to
|
| 344 |
+
expire. If not specified will automatically be set to True on
|
| 345 |
+
UNIX.
|
| 346 |
+
|
| 347 |
+
reuse_port tells the kernel to allow this endpoint to be bound to
|
| 348 |
+
the same port as other existing endpoints are bound to, so long as
|
| 349 |
+
they all set this flag when being created. This option is not
|
| 350 |
+
supported on Windows.
|
| 351 |
+
|
| 352 |
+
ssl_handshake_timeout is the time in seconds that an SSL server
|
| 353 |
+
will wait for completion of the SSL handshake before aborting the
|
| 354 |
+
connection. Default is 60s.
|
| 355 |
+
|
| 356 |
+
start_serving set to True (default) causes the created server
|
| 357 |
+
to start accepting connections immediately. When set to False,
|
| 358 |
+
the user should await Server.start_serving() or Server.serve_forever()
|
| 359 |
+
to make the server to start accepting connections.
|
| 360 |
+
"""
|
| 361 |
+
raise NotImplementedError
|
| 362 |
+
|
| 363 |
+
async def sendfile(self, transport, file, offset=0, count=None,
|
| 364 |
+
*, fallback=True):
|
| 365 |
+
"""Send a file through a transport.
|
| 366 |
+
|
| 367 |
+
Return an amount of sent bytes.
|
| 368 |
+
"""
|
| 369 |
+
raise NotImplementedError
|
| 370 |
+
|
| 371 |
+
async def start_tls(self, transport, protocol, sslcontext, *,
|
| 372 |
+
server_side=False,
|
| 373 |
+
server_hostname=None,
|
| 374 |
+
ssl_handshake_timeout=None):
|
| 375 |
+
"""Upgrade a transport to TLS.
|
| 376 |
+
|
| 377 |
+
Return a new transport that *protocol* should start using
|
| 378 |
+
immediately.
|
| 379 |
+
"""
|
| 380 |
+
raise NotImplementedError
|
| 381 |
+
|
| 382 |
+
async def create_unix_connection(
|
| 383 |
+
self, protocol_factory, path=None, *,
|
| 384 |
+
ssl=None, sock=None,
|
| 385 |
+
server_hostname=None,
|
| 386 |
+
ssl_handshake_timeout=None):
|
| 387 |
+
raise NotImplementedError
|
| 388 |
+
|
| 389 |
+
async def create_unix_server(
|
| 390 |
+
self, protocol_factory, path=None, *,
|
| 391 |
+
sock=None, backlog=100, ssl=None,
|
| 392 |
+
ssl_handshake_timeout=None,
|
| 393 |
+
start_serving=True):
|
| 394 |
+
"""A coroutine which creates a UNIX Domain Socket server.
|
| 395 |
+
|
| 396 |
+
The return value is a Server object, which can be used to stop
|
| 397 |
+
the service.
|
| 398 |
+
|
| 399 |
+
path is a str, representing a file system path to bind the
|
| 400 |
+
server socket to.
|
| 401 |
+
|
| 402 |
+
sock can optionally be specified in order to use a preexisting
|
| 403 |
+
socket object.
|
| 404 |
+
|
| 405 |
+
backlog is the maximum number of queued connections passed to
|
| 406 |
+
listen() (defaults to 100).
|
| 407 |
+
|
| 408 |
+
ssl can be set to an SSLContext to enable SSL over the
|
| 409 |
+
accepted connections.
|
| 410 |
+
|
| 411 |
+
ssl_handshake_timeout is the time in seconds that an SSL server
|
| 412 |
+
will wait for the SSL handshake to complete (defaults to 60s).
|
| 413 |
+
|
| 414 |
+
start_serving set to True (default) causes the created server
|
| 415 |
+
to start accepting connections immediately. When set to False,
|
| 416 |
+
the user should await Server.start_serving() or Server.serve_forever()
|
| 417 |
+
to make the server to start accepting connections.
|
| 418 |
+
"""
|
| 419 |
+
raise NotImplementedError
|
| 420 |
+
|
| 421 |
+
async def connect_accepted_socket(
|
| 422 |
+
self, protocol_factory, sock,
|
| 423 |
+
*, ssl=None,
|
| 424 |
+
ssl_handshake_timeout=None):
|
| 425 |
+
"""Handle an accepted connection.
|
| 426 |
+
|
| 427 |
+
This is used by servers that accept connections outside of
|
| 428 |
+
asyncio, but use asyncio to handle connections.
|
| 429 |
+
|
| 430 |
+
This method is a coroutine. When completed, the coroutine
|
| 431 |
+
returns a (transport, protocol) pair.
|
| 432 |
+
"""
|
| 433 |
+
raise NotImplementedError
|
| 434 |
+
|
| 435 |
+
async def create_datagram_endpoint(self, protocol_factory,
|
| 436 |
+
local_addr=None, remote_addr=None, *,
|
| 437 |
+
family=0, proto=0, flags=0,
|
| 438 |
+
reuse_address=None, reuse_port=None,
|
| 439 |
+
allow_broadcast=None, sock=None):
|
| 440 |
+
"""A coroutine which creates a datagram endpoint.
|
| 441 |
+
|
| 442 |
+
This method will try to establish the endpoint in the background.
|
| 443 |
+
When successful, the coroutine returns a (transport, protocol) pair.
|
| 444 |
+
|
| 445 |
+
protocol_factory must be a callable returning a protocol instance.
|
| 446 |
+
|
| 447 |
+
socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
|
| 448 |
+
host (or family if specified), socket type SOCK_DGRAM.
|
| 449 |
+
|
| 450 |
+
reuse_address tells the kernel to reuse a local socket in
|
| 451 |
+
TIME_WAIT state, without waiting for its natural timeout to
|
| 452 |
+
expire. If not specified it will automatically be set to True on
|
| 453 |
+
UNIX.
|
| 454 |
+
|
| 455 |
+
reuse_port tells the kernel to allow this endpoint to be bound to
|
| 456 |
+
the same port as other existing endpoints are bound to, so long as
|
| 457 |
+
they all set this flag when being created. This option is not
|
| 458 |
+
supported on Windows and some UNIX's. If the
|
| 459 |
+
:py:data:`~socket.SO_REUSEPORT` constant is not defined then this
|
| 460 |
+
capability is unsupported.
|
| 461 |
+
|
| 462 |
+
allow_broadcast tells the kernel to allow this endpoint to send
|
| 463 |
+
messages to the broadcast address.
|
| 464 |
+
|
| 465 |
+
sock can optionally be specified in order to use a preexisting
|
| 466 |
+
socket object.
|
| 467 |
+
"""
|
| 468 |
+
raise NotImplementedError
|
| 469 |
+
|
| 470 |
+
# Pipes and subprocesses.
|
| 471 |
+
|
| 472 |
+
async def connect_read_pipe(self, protocol_factory, pipe):
|
| 473 |
+
"""Register read pipe in event loop. Set the pipe to non-blocking mode.
|
| 474 |
+
|
| 475 |
+
protocol_factory should instantiate object with Protocol interface.
|
| 476 |
+
pipe is a file-like object.
|
| 477 |
+
Return pair (transport, protocol), where transport supports the
|
| 478 |
+
ReadTransport interface."""
|
| 479 |
+
# The reason to accept file-like object instead of just file descriptor
|
| 480 |
+
# is: we need to own pipe and close it at transport finishing
|
| 481 |
+
# Can got complicated errors if pass f.fileno(),
|
| 482 |
+
# close fd in pipe transport then close f and vice versa.
|
| 483 |
+
raise NotImplementedError
|
| 484 |
+
|
| 485 |
+
async def connect_write_pipe(self, protocol_factory, pipe):
|
| 486 |
+
"""Register write pipe in event loop.
|
| 487 |
+
|
| 488 |
+
protocol_factory should instantiate object with BaseProtocol interface.
|
| 489 |
+
Pipe is file-like object already switched to nonblocking.
|
| 490 |
+
Return pair (transport, protocol), where transport support
|
| 491 |
+
WriteTransport interface."""
|
| 492 |
+
# The reason to accept file-like object instead of just file descriptor
|
| 493 |
+
# is: we need to own pipe and close it at transport finishing
|
| 494 |
+
# Can got complicated errors if pass f.fileno(),
|
| 495 |
+
# close fd in pipe transport then close f and vice versa.
|
| 496 |
+
raise NotImplementedError
|
| 497 |
+
|
| 498 |
+
async def subprocess_shell(self, protocol_factory, cmd, *,
|
| 499 |
+
stdin=subprocess.PIPE,
|
| 500 |
+
stdout=subprocess.PIPE,
|
| 501 |
+
stderr=subprocess.PIPE,
|
| 502 |
+
**kwargs):
|
| 503 |
+
raise NotImplementedError
|
| 504 |
+
|
| 505 |
+
async def subprocess_exec(self, protocol_factory, *args,
|
| 506 |
+
stdin=subprocess.PIPE,
|
| 507 |
+
stdout=subprocess.PIPE,
|
| 508 |
+
stderr=subprocess.PIPE,
|
| 509 |
+
**kwargs):
|
| 510 |
+
raise NotImplementedError
|
| 511 |
+
|
| 512 |
+
# Ready-based callback registration methods.
|
| 513 |
+
# The add_*() methods return None.
|
| 514 |
+
# The remove_*() methods return True if something was removed,
|
| 515 |
+
# False if there was nothing to delete.
|
| 516 |
+
|
| 517 |
+
def add_reader(self, fd, callback, *args):
|
| 518 |
+
raise NotImplementedError
|
| 519 |
+
|
| 520 |
+
def remove_reader(self, fd):
|
| 521 |
+
raise NotImplementedError
|
| 522 |
+
|
| 523 |
+
def add_writer(self, fd, callback, *args):
|
| 524 |
+
raise NotImplementedError
|
| 525 |
+
|
| 526 |
+
def remove_writer(self, fd):
|
| 527 |
+
raise NotImplementedError
|
| 528 |
+
|
| 529 |
+
# Completion based I/O methods returning Futures.
|
| 530 |
+
|
| 531 |
+
async def sock_recv(self, sock, nbytes):
|
| 532 |
+
raise NotImplementedError
|
| 533 |
+
|
| 534 |
+
async def sock_recv_into(self, sock, buf):
|
| 535 |
+
raise NotImplementedError
|
| 536 |
+
|
| 537 |
+
async def sock_sendall(self, sock, data):
|
| 538 |
+
raise NotImplementedError
|
| 539 |
+
|
| 540 |
+
async def sock_connect(self, sock, address):
|
| 541 |
+
raise NotImplementedError
|
| 542 |
+
|
| 543 |
+
async def sock_accept(self, sock):
|
| 544 |
+
raise NotImplementedError
|
| 545 |
+
|
| 546 |
+
async def sock_sendfile(self, sock, file, offset=0, count=None,
|
| 547 |
+
*, fallback=None):
|
| 548 |
+
raise NotImplementedError
|
| 549 |
+
|
| 550 |
+
# Signal handling.
|
| 551 |
+
|
| 552 |
+
def add_signal_handler(self, sig, callback, *args):
|
| 553 |
+
raise NotImplementedError
|
| 554 |
+
|
| 555 |
+
def remove_signal_handler(self, sig):
|
| 556 |
+
raise NotImplementedError
|
| 557 |
+
|
| 558 |
+
# Task factory.
|
| 559 |
+
|
| 560 |
+
def set_task_factory(self, factory):
|
| 561 |
+
raise NotImplementedError
|
| 562 |
+
|
| 563 |
+
def get_task_factory(self):
|
| 564 |
+
raise NotImplementedError
|
| 565 |
+
|
| 566 |
+
# Error handlers.
|
| 567 |
+
|
| 568 |
+
def get_exception_handler(self):
|
| 569 |
+
raise NotImplementedError
|
| 570 |
+
|
| 571 |
+
def set_exception_handler(self, handler):
|
| 572 |
+
raise NotImplementedError
|
| 573 |
+
|
| 574 |
+
def default_exception_handler(self, context):
|
| 575 |
+
raise NotImplementedError
|
| 576 |
+
|
| 577 |
+
def call_exception_handler(self, context):
|
| 578 |
+
raise NotImplementedError
|
| 579 |
+
|
| 580 |
+
# Debug flag management.
|
| 581 |
+
|
| 582 |
+
def get_debug(self):
|
| 583 |
+
raise NotImplementedError
|
| 584 |
+
|
| 585 |
+
def set_debug(self, enabled):
|
| 586 |
+
raise NotImplementedError
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
class AbstractEventLoopPolicy:
|
| 590 |
+
"""Abstract policy for accessing the event loop."""
|
| 591 |
+
|
| 592 |
+
def get_event_loop(self):
|
| 593 |
+
"""Get the event loop for the current context.
|
| 594 |
+
|
| 595 |
+
Returns an event loop object implementing the BaseEventLoop interface,
|
| 596 |
+
or raises an exception in case no event loop has been set for the
|
| 597 |
+
current context and the current policy does not specify to create one.
|
| 598 |
+
|
| 599 |
+
It should never return None."""
|
| 600 |
+
raise NotImplementedError
|
| 601 |
+
|
| 602 |
+
def set_event_loop(self, loop):
|
| 603 |
+
"""Set the event loop for the current context to loop."""
|
| 604 |
+
raise NotImplementedError
|
| 605 |
+
|
| 606 |
+
def new_event_loop(self):
|
| 607 |
+
"""Create and return a new event loop object according to this
|
| 608 |
+
policy's rules. If there's need to set this loop as the event loop for
|
| 609 |
+
the current context, set_event_loop must be called explicitly."""
|
| 610 |
+
raise NotImplementedError
|
| 611 |
+
|
| 612 |
+
# Child processes handling (Unix only).
|
| 613 |
+
|
| 614 |
+
def get_child_watcher(self):
|
| 615 |
+
"Get the watcher for child processes."
|
| 616 |
+
raise NotImplementedError
|
| 617 |
+
|
| 618 |
+
def set_child_watcher(self, watcher):
|
| 619 |
+
"""Set the watcher for child processes."""
|
| 620 |
+
raise NotImplementedError
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
|
| 624 |
+
"""Default policy implementation for accessing the event loop.
|
| 625 |
+
|
| 626 |
+
In this policy, each thread has its own event loop. However, we
|
| 627 |
+
only automatically create an event loop by default for the main
|
| 628 |
+
thread; other threads by default have no event loop.
|
| 629 |
+
|
| 630 |
+
Other policies may have different rules (e.g. a single global
|
| 631 |
+
event loop, or automatically creating an event loop per thread, or
|
| 632 |
+
using some other notion of context to which an event loop is
|
| 633 |
+
associated).
|
| 634 |
+
"""
|
| 635 |
+
|
| 636 |
+
_loop_factory = None
|
| 637 |
+
|
| 638 |
+
class _Local(threading.local):
|
| 639 |
+
_loop = None
|
| 640 |
+
_set_called = False
|
| 641 |
+
|
| 642 |
+
def __init__(self):
|
| 643 |
+
self._local = self._Local()
|
| 644 |
+
|
| 645 |
+
def get_event_loop(self):
|
| 646 |
+
"""Get the event loop for the current context.
|
| 647 |
+
|
| 648 |
+
Returns an instance of EventLoop or raises an exception.
|
| 649 |
+
"""
|
| 650 |
+
if (self._local._loop is None and
|
| 651 |
+
not self._local._set_called and
|
| 652 |
+
threading.current_thread() is threading.main_thread()):
|
| 653 |
+
self.set_event_loop(self.new_event_loop())
|
| 654 |
+
|
| 655 |
+
if self._local._loop is None:
|
| 656 |
+
raise RuntimeError('There is no current event loop in thread %r.'
|
| 657 |
+
% threading.current_thread().name)
|
| 658 |
+
|
| 659 |
+
return self._local._loop
|
| 660 |
+
|
| 661 |
+
def set_event_loop(self, loop):
|
| 662 |
+
"""Set the event loop."""
|
| 663 |
+
self._local._set_called = True
|
| 664 |
+
assert loop is None or isinstance(loop, AbstractEventLoop)
|
| 665 |
+
self._local._loop = loop
|
| 666 |
+
|
| 667 |
+
def new_event_loop(self):
|
| 668 |
+
"""Create a new event loop.
|
| 669 |
+
|
| 670 |
+
You must call set_event_loop() to make this the current event
|
| 671 |
+
loop.
|
| 672 |
+
"""
|
| 673 |
+
return self._loop_factory()
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
# Event loop policy. The policy itself is always global, even if the
|
| 677 |
+
# policy's rules say that there is an event loop per thread (or other
|
| 678 |
+
# notion of context). The default policy is installed by the first
|
| 679 |
+
# call to get_event_loop_policy().
|
| 680 |
+
_event_loop_policy = None
|
| 681 |
+
|
| 682 |
+
# Lock for protecting the on-the-fly creation of the event loop policy.
|
| 683 |
+
_lock = threading.Lock()
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
# A TLS for the running event loop, used by _get_running_loop.
|
| 687 |
+
class _RunningLoop(threading.local):
|
| 688 |
+
loop_pid = (None, None)
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
_running_loop = _RunningLoop()
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
def get_running_loop():
|
| 695 |
+
"""Return the running event loop. Raise a RuntimeError if there is none.
|
| 696 |
+
|
| 697 |
+
This function is thread-specific.
|
| 698 |
+
"""
|
| 699 |
+
# NOTE: this function is implemented in C (see _asynciomodule.c)
|
| 700 |
+
loop = _get_running_loop()
|
| 701 |
+
if loop is None:
|
| 702 |
+
raise RuntimeError('no running event loop')
|
| 703 |
+
return loop
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def _get_running_loop():
|
| 707 |
+
"""Return the running event loop or None.
|
| 708 |
+
|
| 709 |
+
This is a low-level function intended to be used by event loops.
|
| 710 |
+
This function is thread-specific.
|
| 711 |
+
"""
|
| 712 |
+
# NOTE: this function is implemented in C (see _asynciomodule.c)
|
| 713 |
+
running_loop, pid = _running_loop.loop_pid
|
| 714 |
+
if running_loop is not None and pid == os.getpid():
|
| 715 |
+
return running_loop
|
| 716 |
+
|
| 717 |
+
|
| 718 |
+
def _set_running_loop(loop):
|
| 719 |
+
"""Set the running event loop.
|
| 720 |
+
|
| 721 |
+
This is a low-level function intended to be used by event loops.
|
| 722 |
+
This function is thread-specific.
|
| 723 |
+
"""
|
| 724 |
+
# NOTE: this function is implemented in C (see _asynciomodule.c)
|
| 725 |
+
_running_loop.loop_pid = (loop, os.getpid())
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
def _init_event_loop_policy():
|
| 729 |
+
global _event_loop_policy
|
| 730 |
+
with _lock:
|
| 731 |
+
if _event_loop_policy is None: # pragma: no branch
|
| 732 |
+
from . import DefaultEventLoopPolicy
|
| 733 |
+
_event_loop_policy = DefaultEventLoopPolicy()
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
def get_event_loop_policy():
|
| 737 |
+
"""Get the current event loop policy."""
|
| 738 |
+
if _event_loop_policy is None:
|
| 739 |
+
_init_event_loop_policy()
|
| 740 |
+
return _event_loop_policy
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def set_event_loop_policy(policy):
|
| 744 |
+
"""Set the current event loop policy.
|
| 745 |
+
|
| 746 |
+
If policy is None, the default policy is restored."""
|
| 747 |
+
global _event_loop_policy
|
| 748 |
+
assert policy is None or isinstance(policy, AbstractEventLoopPolicy)
|
| 749 |
+
_event_loop_policy = policy
|
| 750 |
+
|
| 751 |
+
|
| 752 |
+
def get_event_loop():
|
| 753 |
+
"""Return an asyncio event loop.
|
| 754 |
+
|
| 755 |
+
When called from a coroutine or a callback (e.g. scheduled with call_soon
|
| 756 |
+
or similar API), this function will always return the running event loop.
|
| 757 |
+
|
| 758 |
+
If there is no running event loop set, the function will return
|
| 759 |
+
the result of `get_event_loop_policy().get_event_loop()` call.
|
| 760 |
+
"""
|
| 761 |
+
# NOTE: this function is implemented in C (see _asynciomodule.c)
|
| 762 |
+
return _py__get_event_loop()
|
| 763 |
+
|
| 764 |
+
|
| 765 |
+
def _get_event_loop(stacklevel=3):
|
| 766 |
+
# This internal method is going away in Python 3.12, left here only for
|
| 767 |
+
# backwards compatibility with 3.10.0 - 3.10.8 and 3.11.0.
|
| 768 |
+
# Similarly, this method's C equivalent in _asyncio is going away as well.
|
| 769 |
+
# See GH-99949 for more details.
|
| 770 |
+
current_loop = _get_running_loop()
|
| 771 |
+
if current_loop is not None:
|
| 772 |
+
return current_loop
|
| 773 |
+
return get_event_loop_policy().get_event_loop()
|
| 774 |
+
|
| 775 |
+
|
| 776 |
+
def set_event_loop(loop):
|
| 777 |
+
"""Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
|
| 778 |
+
get_event_loop_policy().set_event_loop(loop)
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
def new_event_loop():
|
| 782 |
+
"""Equivalent to calling get_event_loop_policy().new_event_loop()."""
|
| 783 |
+
return get_event_loop_policy().new_event_loop()
|
| 784 |
+
|
| 785 |
+
|
| 786 |
+
def get_child_watcher():
|
| 787 |
+
"""Equivalent to calling get_event_loop_policy().get_child_watcher()."""
|
| 788 |
+
return get_event_loop_policy().get_child_watcher()
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
def set_child_watcher(watcher):
|
| 792 |
+
"""Equivalent to calling
|
| 793 |
+
get_event_loop_policy().set_child_watcher(watcher)."""
|
| 794 |
+
return get_event_loop_policy().set_child_watcher(watcher)
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
# Alias pure-Python implementations for testing purposes.
|
| 798 |
+
_py__get_running_loop = _get_running_loop
|
| 799 |
+
_py__set_running_loop = _set_running_loop
|
| 800 |
+
_py_get_running_loop = get_running_loop
|
| 801 |
+
_py_get_event_loop = get_event_loop
|
| 802 |
+
_py__get_event_loop = _get_event_loop
|
| 803 |
+
|
| 804 |
+
|
| 805 |
+
try:
|
| 806 |
+
# get_event_loop() is one of the most frequently called
|
| 807 |
+
# functions in asyncio. Pure Python implementation is
|
| 808 |
+
# about 4 times slower than C-accelerated.
|
| 809 |
+
from _asyncio import (_get_running_loop, _set_running_loop,
|
| 810 |
+
get_running_loop, get_event_loop, _get_event_loop)
|
| 811 |
+
except ImportError:
|
| 812 |
+
pass
|
| 813 |
+
else:
|
| 814 |
+
# Alias C implementations for testing purposes.
|
| 815 |
+
_c__get_running_loop = _get_running_loop
|
| 816 |
+
_c__set_running_loop = _set_running_loop
|
| 817 |
+
_c_get_running_loop = get_running_loop
|
| 818 |
+
_c_get_event_loop = get_event_loop
|
| 819 |
+
_c__get_event_loop = _get_event_loop
|
janus/lib/python3.10/asyncio/exceptions.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""asyncio exceptions."""
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
__all__ = ('CancelledError', 'InvalidStateError', 'TimeoutError',
|
| 5 |
+
'IncompleteReadError', 'LimitOverrunError',
|
| 6 |
+
'SendfileNotAvailableError')
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class CancelledError(BaseException):
|
| 10 |
+
"""The Future or Task was cancelled."""
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TimeoutError(Exception):
|
| 14 |
+
"""The operation exceeded the given deadline."""
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class InvalidStateError(Exception):
|
| 18 |
+
"""The operation is not allowed in this state."""
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class SendfileNotAvailableError(RuntimeError):
|
| 22 |
+
"""Sendfile syscall is not available.
|
| 23 |
+
|
| 24 |
+
Raised if OS does not support sendfile syscall for given socket or
|
| 25 |
+
file type.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class IncompleteReadError(EOFError):
|
| 30 |
+
"""
|
| 31 |
+
Incomplete read error. Attributes:
|
| 32 |
+
|
| 33 |
+
- partial: read bytes string before the end of stream was reached
|
| 34 |
+
- expected: total number of expected bytes (or None if unknown)
|
| 35 |
+
"""
|
| 36 |
+
def __init__(self, partial, expected):
|
| 37 |
+
r_expected = 'undefined' if expected is None else repr(expected)
|
| 38 |
+
super().__init__(f'{len(partial)} bytes read on a total of '
|
| 39 |
+
f'{r_expected} expected bytes')
|
| 40 |
+
self.partial = partial
|
| 41 |
+
self.expected = expected
|
| 42 |
+
|
| 43 |
+
def __reduce__(self):
|
| 44 |
+
return type(self), (self.partial, self.expected)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class LimitOverrunError(Exception):
|
| 48 |
+
"""Reached the buffer limit while looking for a separator.
|
| 49 |
+
|
| 50 |
+
Attributes:
|
| 51 |
+
- consumed: total number of to be consumed bytes.
|
| 52 |
+
"""
|
| 53 |
+
def __init__(self, message, consumed):
|
| 54 |
+
super().__init__(message)
|
| 55 |
+
self.consumed = consumed
|
| 56 |
+
|
| 57 |
+
def __reduce__(self):
|
| 58 |
+
return type(self), (self.args[0], self.consumed)
|
janus/lib/python3.10/asyncio/format_helpers.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
import inspect
|
| 3 |
+
import reprlib
|
| 4 |
+
import sys
|
| 5 |
+
import traceback
|
| 6 |
+
|
| 7 |
+
from . import constants
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _get_function_source(func):
|
| 11 |
+
func = inspect.unwrap(func)
|
| 12 |
+
if inspect.isfunction(func):
|
| 13 |
+
code = func.__code__
|
| 14 |
+
return (code.co_filename, code.co_firstlineno)
|
| 15 |
+
if isinstance(func, functools.partial):
|
| 16 |
+
return _get_function_source(func.func)
|
| 17 |
+
if isinstance(func, functools.partialmethod):
|
| 18 |
+
return _get_function_source(func.func)
|
| 19 |
+
return None
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _format_callback_source(func, args):
|
| 23 |
+
func_repr = _format_callback(func, args, None)
|
| 24 |
+
source = _get_function_source(func)
|
| 25 |
+
if source:
|
| 26 |
+
func_repr += f' at {source[0]}:{source[1]}'
|
| 27 |
+
return func_repr
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _format_args_and_kwargs(args, kwargs):
|
| 31 |
+
"""Format function arguments and keyword arguments.
|
| 32 |
+
|
| 33 |
+
Special case for a single parameter: ('hello',) is formatted as ('hello').
|
| 34 |
+
"""
|
| 35 |
+
# use reprlib to limit the length of the output
|
| 36 |
+
items = []
|
| 37 |
+
if args:
|
| 38 |
+
items.extend(reprlib.repr(arg) for arg in args)
|
| 39 |
+
if kwargs:
|
| 40 |
+
items.extend(f'{k}={reprlib.repr(v)}' for k, v in kwargs.items())
|
| 41 |
+
return '({})'.format(', '.join(items))
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _format_callback(func, args, kwargs, suffix=''):
|
| 45 |
+
if isinstance(func, functools.partial):
|
| 46 |
+
suffix = _format_args_and_kwargs(args, kwargs) + suffix
|
| 47 |
+
return _format_callback(func.func, func.args, func.keywords, suffix)
|
| 48 |
+
|
| 49 |
+
if hasattr(func, '__qualname__') and func.__qualname__:
|
| 50 |
+
func_repr = func.__qualname__
|
| 51 |
+
elif hasattr(func, '__name__') and func.__name__:
|
| 52 |
+
func_repr = func.__name__
|
| 53 |
+
else:
|
| 54 |
+
func_repr = repr(func)
|
| 55 |
+
|
| 56 |
+
func_repr += _format_args_and_kwargs(args, kwargs)
|
| 57 |
+
if suffix:
|
| 58 |
+
func_repr += suffix
|
| 59 |
+
return func_repr
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def extract_stack(f=None, limit=None):
|
| 63 |
+
"""Replacement for traceback.extract_stack() that only does the
|
| 64 |
+
necessary work for asyncio debug mode.
|
| 65 |
+
"""
|
| 66 |
+
if f is None:
|
| 67 |
+
f = sys._getframe().f_back
|
| 68 |
+
if limit is None:
|
| 69 |
+
# Limit the amount of work to a reasonable amount, as extract_stack()
|
| 70 |
+
# can be called for each coroutine and future in debug mode.
|
| 71 |
+
limit = constants.DEBUG_STACK_DEPTH
|
| 72 |
+
stack = traceback.StackSummary.extract(traceback.walk_stack(f),
|
| 73 |
+
limit=limit,
|
| 74 |
+
lookup_lines=False)
|
| 75 |
+
stack.reverse()
|
| 76 |
+
return stack
|
janus/lib/python3.10/asyncio/futures.py
ADDED
|
@@ -0,0 +1,426 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A Future class similar to the one in PEP 3148."""
|
| 2 |
+
|
| 3 |
+
__all__ = (
|
| 4 |
+
'Future', 'wrap_future', 'isfuture',
|
| 5 |
+
)
|
| 6 |
+
|
| 7 |
+
import concurrent.futures
|
| 8 |
+
import contextvars
|
| 9 |
+
import logging
|
| 10 |
+
import sys
|
| 11 |
+
from types import GenericAlias
|
| 12 |
+
|
| 13 |
+
from . import base_futures
|
| 14 |
+
from . import events
|
| 15 |
+
from . import exceptions
|
| 16 |
+
from . import format_helpers
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
isfuture = base_futures.isfuture
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
_PENDING = base_futures._PENDING
|
| 23 |
+
_CANCELLED = base_futures._CANCELLED
|
| 24 |
+
_FINISHED = base_futures._FINISHED
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
STACK_DEBUG = logging.DEBUG - 1 # heavy-duty debugging
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Future:
|
| 31 |
+
"""This class is *almost* compatible with concurrent.futures.Future.
|
| 32 |
+
|
| 33 |
+
Differences:
|
| 34 |
+
|
| 35 |
+
- This class is not thread-safe.
|
| 36 |
+
|
| 37 |
+
- result() and exception() do not take a timeout argument and
|
| 38 |
+
raise an exception when the future isn't done yet.
|
| 39 |
+
|
| 40 |
+
- Callbacks registered with add_done_callback() are always called
|
| 41 |
+
via the event loop's call_soon().
|
| 42 |
+
|
| 43 |
+
- This class is not compatible with the wait() and as_completed()
|
| 44 |
+
methods in the concurrent.futures package.
|
| 45 |
+
|
| 46 |
+
(In Python 3.4 or later we may be able to unify the implementations.)
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
# Class variables serving as defaults for instance variables.
|
| 50 |
+
_state = _PENDING
|
| 51 |
+
_result = None
|
| 52 |
+
_exception = None
|
| 53 |
+
_loop = None
|
| 54 |
+
_source_traceback = None
|
| 55 |
+
_cancel_message = None
|
| 56 |
+
# A saved CancelledError for later chaining as an exception context.
|
| 57 |
+
_cancelled_exc = None
|
| 58 |
+
|
| 59 |
+
# This field is used for a dual purpose:
|
| 60 |
+
# - Its presence is a marker to declare that a class implements
|
| 61 |
+
# the Future protocol (i.e. is intended to be duck-type compatible).
|
| 62 |
+
# The value must also be not-None, to enable a subclass to declare
|
| 63 |
+
# that it is not compatible by setting this to None.
|
| 64 |
+
# - It is set by __iter__() below so that Task._step() can tell
|
| 65 |
+
# the difference between
|
| 66 |
+
# `await Future()` or`yield from Future()` (correct) vs.
|
| 67 |
+
# `yield Future()` (incorrect).
|
| 68 |
+
_asyncio_future_blocking = False
|
| 69 |
+
|
| 70 |
+
__log_traceback = False
|
| 71 |
+
|
| 72 |
+
def __init__(self, *, loop=None):
|
| 73 |
+
"""Initialize the future.
|
| 74 |
+
|
| 75 |
+
The optional event_loop argument allows explicitly setting the event
|
| 76 |
+
loop object used by the future. If it's not provided, the future uses
|
| 77 |
+
the default event loop.
|
| 78 |
+
"""
|
| 79 |
+
if loop is None:
|
| 80 |
+
self._loop = events._get_event_loop()
|
| 81 |
+
else:
|
| 82 |
+
self._loop = loop
|
| 83 |
+
self._callbacks = []
|
| 84 |
+
if self._loop.get_debug():
|
| 85 |
+
self._source_traceback = format_helpers.extract_stack(
|
| 86 |
+
sys._getframe(1))
|
| 87 |
+
|
| 88 |
+
_repr_info = base_futures._future_repr_info
|
| 89 |
+
|
| 90 |
+
def __repr__(self):
|
| 91 |
+
return '<{} {}>'.format(self.__class__.__name__,
|
| 92 |
+
' '.join(self._repr_info()))
|
| 93 |
+
|
| 94 |
+
def __del__(self):
|
| 95 |
+
if not self.__log_traceback:
|
| 96 |
+
# set_exception() was not called, or result() or exception()
|
| 97 |
+
# has consumed the exception
|
| 98 |
+
return
|
| 99 |
+
exc = self._exception
|
| 100 |
+
context = {
|
| 101 |
+
'message':
|
| 102 |
+
f'{self.__class__.__name__} exception was never retrieved',
|
| 103 |
+
'exception': exc,
|
| 104 |
+
'future': self,
|
| 105 |
+
}
|
| 106 |
+
if self._source_traceback:
|
| 107 |
+
context['source_traceback'] = self._source_traceback
|
| 108 |
+
self._loop.call_exception_handler(context)
|
| 109 |
+
|
| 110 |
+
__class_getitem__ = classmethod(GenericAlias)
|
| 111 |
+
|
| 112 |
+
@property
|
| 113 |
+
def _log_traceback(self):
|
| 114 |
+
return self.__log_traceback
|
| 115 |
+
|
| 116 |
+
@_log_traceback.setter
|
| 117 |
+
def _log_traceback(self, val):
|
| 118 |
+
if val:
|
| 119 |
+
raise ValueError('_log_traceback can only be set to False')
|
| 120 |
+
self.__log_traceback = False
|
| 121 |
+
|
| 122 |
+
def get_loop(self):
|
| 123 |
+
"""Return the event loop the Future is bound to."""
|
| 124 |
+
loop = self._loop
|
| 125 |
+
if loop is None:
|
| 126 |
+
raise RuntimeError("Future object is not initialized.")
|
| 127 |
+
return loop
|
| 128 |
+
|
| 129 |
+
def _make_cancelled_error(self):
|
| 130 |
+
"""Create the CancelledError to raise if the Future is cancelled.
|
| 131 |
+
|
| 132 |
+
This should only be called once when handling a cancellation since
|
| 133 |
+
it erases the saved context exception value.
|
| 134 |
+
"""
|
| 135 |
+
if self._cancel_message is None:
|
| 136 |
+
exc = exceptions.CancelledError()
|
| 137 |
+
else:
|
| 138 |
+
exc = exceptions.CancelledError(self._cancel_message)
|
| 139 |
+
exc.__context__ = self._cancelled_exc
|
| 140 |
+
# Remove the reference since we don't need this anymore.
|
| 141 |
+
self._cancelled_exc = None
|
| 142 |
+
return exc
|
| 143 |
+
|
| 144 |
+
def cancel(self, msg=None):
|
| 145 |
+
"""Cancel the future and schedule callbacks.
|
| 146 |
+
|
| 147 |
+
If the future is already done or cancelled, return False. Otherwise,
|
| 148 |
+
change the future's state to cancelled, schedule the callbacks and
|
| 149 |
+
return True.
|
| 150 |
+
"""
|
| 151 |
+
self.__log_traceback = False
|
| 152 |
+
if self._state != _PENDING:
|
| 153 |
+
return False
|
| 154 |
+
self._state = _CANCELLED
|
| 155 |
+
self._cancel_message = msg
|
| 156 |
+
self.__schedule_callbacks()
|
| 157 |
+
return True
|
| 158 |
+
|
| 159 |
+
def __schedule_callbacks(self):
|
| 160 |
+
"""Internal: Ask the event loop to call all callbacks.
|
| 161 |
+
|
| 162 |
+
The callbacks are scheduled to be called as soon as possible. Also
|
| 163 |
+
clears the callback list.
|
| 164 |
+
"""
|
| 165 |
+
callbacks = self._callbacks[:]
|
| 166 |
+
if not callbacks:
|
| 167 |
+
return
|
| 168 |
+
|
| 169 |
+
self._callbacks[:] = []
|
| 170 |
+
for callback, ctx in callbacks:
|
| 171 |
+
self._loop.call_soon(callback, self, context=ctx)
|
| 172 |
+
|
| 173 |
+
def cancelled(self):
|
| 174 |
+
"""Return True if the future was cancelled."""
|
| 175 |
+
return self._state == _CANCELLED
|
| 176 |
+
|
| 177 |
+
# Don't implement running(); see http://bugs.python.org/issue18699
|
| 178 |
+
|
| 179 |
+
def done(self):
|
| 180 |
+
"""Return True if the future is done.
|
| 181 |
+
|
| 182 |
+
Done means either that a result / exception are available, or that the
|
| 183 |
+
future was cancelled.
|
| 184 |
+
"""
|
| 185 |
+
return self._state != _PENDING
|
| 186 |
+
|
| 187 |
+
def result(self):
|
| 188 |
+
"""Return the result this future represents.
|
| 189 |
+
|
| 190 |
+
If the future has been cancelled, raises CancelledError. If the
|
| 191 |
+
future's result isn't yet available, raises InvalidStateError. If
|
| 192 |
+
the future is done and has an exception set, this exception is raised.
|
| 193 |
+
"""
|
| 194 |
+
if self._state == _CANCELLED:
|
| 195 |
+
exc = self._make_cancelled_error()
|
| 196 |
+
raise exc
|
| 197 |
+
if self._state != _FINISHED:
|
| 198 |
+
raise exceptions.InvalidStateError('Result is not ready.')
|
| 199 |
+
self.__log_traceback = False
|
| 200 |
+
if self._exception is not None:
|
| 201 |
+
raise self._exception.with_traceback(self._exception_tb)
|
| 202 |
+
return self._result
|
| 203 |
+
|
| 204 |
+
def exception(self):
|
| 205 |
+
"""Return the exception that was set on this future.
|
| 206 |
+
|
| 207 |
+
The exception (or None if no exception was set) is returned only if
|
| 208 |
+
the future is done. If the future has been cancelled, raises
|
| 209 |
+
CancelledError. If the future isn't done yet, raises
|
| 210 |
+
InvalidStateError.
|
| 211 |
+
"""
|
| 212 |
+
if self._state == _CANCELLED:
|
| 213 |
+
exc = self._make_cancelled_error()
|
| 214 |
+
raise exc
|
| 215 |
+
if self._state != _FINISHED:
|
| 216 |
+
raise exceptions.InvalidStateError('Exception is not set.')
|
| 217 |
+
self.__log_traceback = False
|
| 218 |
+
return self._exception
|
| 219 |
+
|
| 220 |
+
def add_done_callback(self, fn, *, context=None):
|
| 221 |
+
"""Add a callback to be run when the future becomes done.
|
| 222 |
+
|
| 223 |
+
The callback is called with a single argument - the future object. If
|
| 224 |
+
the future is already done when this is called, the callback is
|
| 225 |
+
scheduled with call_soon.
|
| 226 |
+
"""
|
| 227 |
+
if self._state != _PENDING:
|
| 228 |
+
self._loop.call_soon(fn, self, context=context)
|
| 229 |
+
else:
|
| 230 |
+
if context is None:
|
| 231 |
+
context = contextvars.copy_context()
|
| 232 |
+
self._callbacks.append((fn, context))
|
| 233 |
+
|
| 234 |
+
# New method not in PEP 3148.
|
| 235 |
+
|
| 236 |
+
def remove_done_callback(self, fn):
|
| 237 |
+
"""Remove all instances of a callback from the "call when done" list.
|
| 238 |
+
|
| 239 |
+
Returns the number of callbacks removed.
|
| 240 |
+
"""
|
| 241 |
+
filtered_callbacks = [(f, ctx)
|
| 242 |
+
for (f, ctx) in self._callbacks
|
| 243 |
+
if f != fn]
|
| 244 |
+
removed_count = len(self._callbacks) - len(filtered_callbacks)
|
| 245 |
+
if removed_count:
|
| 246 |
+
self._callbacks[:] = filtered_callbacks
|
| 247 |
+
return removed_count
|
| 248 |
+
|
| 249 |
+
# So-called internal methods (note: no set_running_or_notify_cancel()).
|
| 250 |
+
|
| 251 |
+
def set_result(self, result):
|
| 252 |
+
"""Mark the future done and set its result.
|
| 253 |
+
|
| 254 |
+
If the future is already done when this method is called, raises
|
| 255 |
+
InvalidStateError.
|
| 256 |
+
"""
|
| 257 |
+
if self._state != _PENDING:
|
| 258 |
+
raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
|
| 259 |
+
self._result = result
|
| 260 |
+
self._state = _FINISHED
|
| 261 |
+
self.__schedule_callbacks()
|
| 262 |
+
|
| 263 |
+
def set_exception(self, exception):
|
| 264 |
+
"""Mark the future done and set an exception.
|
| 265 |
+
|
| 266 |
+
If the future is already done when this method is called, raises
|
| 267 |
+
InvalidStateError.
|
| 268 |
+
"""
|
| 269 |
+
if self._state != _PENDING:
|
| 270 |
+
raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
|
| 271 |
+
if isinstance(exception, type):
|
| 272 |
+
exception = exception()
|
| 273 |
+
if type(exception) is StopIteration:
|
| 274 |
+
raise TypeError("StopIteration interacts badly with generators "
|
| 275 |
+
"and cannot be raised into a Future")
|
| 276 |
+
self._exception = exception
|
| 277 |
+
self._exception_tb = exception.__traceback__
|
| 278 |
+
self._state = _FINISHED
|
| 279 |
+
self.__schedule_callbacks()
|
| 280 |
+
self.__log_traceback = True
|
| 281 |
+
|
| 282 |
+
def __await__(self):
|
| 283 |
+
if not self.done():
|
| 284 |
+
self._asyncio_future_blocking = True
|
| 285 |
+
yield self # This tells Task to wait for completion.
|
| 286 |
+
if not self.done():
|
| 287 |
+
raise RuntimeError("await wasn't used with future")
|
| 288 |
+
return self.result() # May raise too.
|
| 289 |
+
|
| 290 |
+
__iter__ = __await__ # make compatible with 'yield from'.
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
# Needed for testing purposes.
|
| 294 |
+
_PyFuture = Future
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def _get_loop(fut):
|
| 298 |
+
# Tries to call Future.get_loop() if it's available.
|
| 299 |
+
# Otherwise fallbacks to using the old '_loop' property.
|
| 300 |
+
try:
|
| 301 |
+
get_loop = fut.get_loop
|
| 302 |
+
except AttributeError:
|
| 303 |
+
pass
|
| 304 |
+
else:
|
| 305 |
+
return get_loop()
|
| 306 |
+
return fut._loop
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def _set_result_unless_cancelled(fut, result):
|
| 310 |
+
"""Helper setting the result only if the future was not cancelled."""
|
| 311 |
+
if fut.cancelled():
|
| 312 |
+
return
|
| 313 |
+
fut.set_result(result)
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def _convert_future_exc(exc):
|
| 317 |
+
exc_class = type(exc)
|
| 318 |
+
if exc_class is concurrent.futures.CancelledError:
|
| 319 |
+
return exceptions.CancelledError(*exc.args)
|
| 320 |
+
elif exc_class is concurrent.futures.TimeoutError:
|
| 321 |
+
return exceptions.TimeoutError(*exc.args)
|
| 322 |
+
elif exc_class is concurrent.futures.InvalidStateError:
|
| 323 |
+
return exceptions.InvalidStateError(*exc.args)
|
| 324 |
+
else:
|
| 325 |
+
return exc
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def _set_concurrent_future_state(concurrent, source):
|
| 329 |
+
"""Copy state from a future to a concurrent.futures.Future."""
|
| 330 |
+
assert source.done()
|
| 331 |
+
if source.cancelled():
|
| 332 |
+
concurrent.cancel()
|
| 333 |
+
if not concurrent.set_running_or_notify_cancel():
|
| 334 |
+
return
|
| 335 |
+
exception = source.exception()
|
| 336 |
+
if exception is not None:
|
| 337 |
+
concurrent.set_exception(_convert_future_exc(exception))
|
| 338 |
+
else:
|
| 339 |
+
result = source.result()
|
| 340 |
+
concurrent.set_result(result)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def _copy_future_state(source, dest):
|
| 344 |
+
"""Internal helper to copy state from another Future.
|
| 345 |
+
|
| 346 |
+
The other Future may be a concurrent.futures.Future.
|
| 347 |
+
"""
|
| 348 |
+
assert source.done()
|
| 349 |
+
if dest.cancelled():
|
| 350 |
+
return
|
| 351 |
+
assert not dest.done()
|
| 352 |
+
if source.cancelled():
|
| 353 |
+
dest.cancel()
|
| 354 |
+
else:
|
| 355 |
+
exception = source.exception()
|
| 356 |
+
if exception is not None:
|
| 357 |
+
dest.set_exception(_convert_future_exc(exception))
|
| 358 |
+
else:
|
| 359 |
+
result = source.result()
|
| 360 |
+
dest.set_result(result)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def _chain_future(source, destination):
|
| 364 |
+
"""Chain two futures so that when one completes, so does the other.
|
| 365 |
+
|
| 366 |
+
The result (or exception) of source will be copied to destination.
|
| 367 |
+
If destination is cancelled, source gets cancelled too.
|
| 368 |
+
Compatible with both asyncio.Future and concurrent.futures.Future.
|
| 369 |
+
"""
|
| 370 |
+
if not isfuture(source) and not isinstance(source,
|
| 371 |
+
concurrent.futures.Future):
|
| 372 |
+
raise TypeError('A future is required for source argument')
|
| 373 |
+
if not isfuture(destination) and not isinstance(destination,
|
| 374 |
+
concurrent.futures.Future):
|
| 375 |
+
raise TypeError('A future is required for destination argument')
|
| 376 |
+
source_loop = _get_loop(source) if isfuture(source) else None
|
| 377 |
+
dest_loop = _get_loop(destination) if isfuture(destination) else None
|
| 378 |
+
|
| 379 |
+
def _set_state(future, other):
|
| 380 |
+
if isfuture(future):
|
| 381 |
+
_copy_future_state(other, future)
|
| 382 |
+
else:
|
| 383 |
+
_set_concurrent_future_state(future, other)
|
| 384 |
+
|
| 385 |
+
def _call_check_cancel(destination):
|
| 386 |
+
if destination.cancelled():
|
| 387 |
+
if source_loop is None or source_loop is dest_loop:
|
| 388 |
+
source.cancel()
|
| 389 |
+
else:
|
| 390 |
+
source_loop.call_soon_threadsafe(source.cancel)
|
| 391 |
+
|
| 392 |
+
def _call_set_state(source):
|
| 393 |
+
if (destination.cancelled() and
|
| 394 |
+
dest_loop is not None and dest_loop.is_closed()):
|
| 395 |
+
return
|
| 396 |
+
if dest_loop is None or dest_loop is source_loop:
|
| 397 |
+
_set_state(destination, source)
|
| 398 |
+
else:
|
| 399 |
+
if dest_loop.is_closed():
|
| 400 |
+
return
|
| 401 |
+
dest_loop.call_soon_threadsafe(_set_state, destination, source)
|
| 402 |
+
|
| 403 |
+
destination.add_done_callback(_call_check_cancel)
|
| 404 |
+
source.add_done_callback(_call_set_state)
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def wrap_future(future, *, loop=None):
|
| 408 |
+
"""Wrap concurrent.futures.Future object."""
|
| 409 |
+
if isfuture(future):
|
| 410 |
+
return future
|
| 411 |
+
assert isinstance(future, concurrent.futures.Future), \
|
| 412 |
+
f'concurrent.futures.Future is expected, got {future!r}'
|
| 413 |
+
if loop is None:
|
| 414 |
+
loop = events._get_event_loop()
|
| 415 |
+
new_future = loop.create_future()
|
| 416 |
+
_chain_future(future, new_future)
|
| 417 |
+
return new_future
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
try:
|
| 421 |
+
import _asyncio
|
| 422 |
+
except ImportError:
|
| 423 |
+
pass
|
| 424 |
+
else:
|
| 425 |
+
# _CFuture is needed for tests.
|
| 426 |
+
Future = _CFuture = _asyncio.Future
|
janus/lib/python3.10/asyncio/locks.py
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Synchronization primitives."""
|
| 2 |
+
|
| 3 |
+
__all__ = ('Lock', 'Event', 'Condition', 'Semaphore', 'BoundedSemaphore')
|
| 4 |
+
|
| 5 |
+
import collections
|
| 6 |
+
|
| 7 |
+
from . import exceptions
|
| 8 |
+
from . import mixins
|
| 9 |
+
from . import tasks
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class _ContextManagerMixin:
|
| 13 |
+
async def __aenter__(self):
|
| 14 |
+
await self.acquire()
|
| 15 |
+
# We have no use for the "as ..." clause in the with
|
| 16 |
+
# statement for locks.
|
| 17 |
+
return None
|
| 18 |
+
|
| 19 |
+
async def __aexit__(self, exc_type, exc, tb):
|
| 20 |
+
self.release()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class Lock(_ContextManagerMixin, mixins._LoopBoundMixin):
|
| 24 |
+
"""Primitive lock objects.
|
| 25 |
+
|
| 26 |
+
A primitive lock is a synchronization primitive that is not owned
|
| 27 |
+
by a particular coroutine when locked. A primitive lock is in one
|
| 28 |
+
of two states, 'locked' or 'unlocked'.
|
| 29 |
+
|
| 30 |
+
It is created in the unlocked state. It has two basic methods,
|
| 31 |
+
acquire() and release(). When the state is unlocked, acquire()
|
| 32 |
+
changes the state to locked and returns immediately. When the
|
| 33 |
+
state is locked, acquire() blocks until a call to release() in
|
| 34 |
+
another coroutine changes it to unlocked, then the acquire() call
|
| 35 |
+
resets it to locked and returns. The release() method should only
|
| 36 |
+
be called in the locked state; it changes the state to unlocked
|
| 37 |
+
and returns immediately. If an attempt is made to release an
|
| 38 |
+
unlocked lock, a RuntimeError will be raised.
|
| 39 |
+
|
| 40 |
+
When more than one coroutine is blocked in acquire() waiting for
|
| 41 |
+
the state to turn to unlocked, only one coroutine proceeds when a
|
| 42 |
+
release() call resets the state to unlocked; first coroutine which
|
| 43 |
+
is blocked in acquire() is being processed.
|
| 44 |
+
|
| 45 |
+
acquire() is a coroutine and should be called with 'await'.
|
| 46 |
+
|
| 47 |
+
Locks also support the asynchronous context management protocol.
|
| 48 |
+
'async with lock' statement should be used.
|
| 49 |
+
|
| 50 |
+
Usage:
|
| 51 |
+
|
| 52 |
+
lock = Lock()
|
| 53 |
+
...
|
| 54 |
+
await lock.acquire()
|
| 55 |
+
try:
|
| 56 |
+
...
|
| 57 |
+
finally:
|
| 58 |
+
lock.release()
|
| 59 |
+
|
| 60 |
+
Context manager usage:
|
| 61 |
+
|
| 62 |
+
lock = Lock()
|
| 63 |
+
...
|
| 64 |
+
async with lock:
|
| 65 |
+
...
|
| 66 |
+
|
| 67 |
+
Lock objects can be tested for locking state:
|
| 68 |
+
|
| 69 |
+
if not lock.locked():
|
| 70 |
+
await lock.acquire()
|
| 71 |
+
else:
|
| 72 |
+
# lock is acquired
|
| 73 |
+
...
|
| 74 |
+
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
def __init__(self, *, loop=mixins._marker):
|
| 78 |
+
super().__init__(loop=loop)
|
| 79 |
+
self._waiters = None
|
| 80 |
+
self._locked = False
|
| 81 |
+
|
| 82 |
+
def __repr__(self):
|
| 83 |
+
res = super().__repr__()
|
| 84 |
+
extra = 'locked' if self._locked else 'unlocked'
|
| 85 |
+
if self._waiters:
|
| 86 |
+
extra = f'{extra}, waiters:{len(self._waiters)}'
|
| 87 |
+
return f'<{res[1:-1]} [{extra}]>'
|
| 88 |
+
|
| 89 |
+
def locked(self):
|
| 90 |
+
"""Return True if lock is acquired."""
|
| 91 |
+
return self._locked
|
| 92 |
+
|
| 93 |
+
async def acquire(self):
|
| 94 |
+
"""Acquire a lock.
|
| 95 |
+
|
| 96 |
+
This method blocks until the lock is unlocked, then sets it to
|
| 97 |
+
locked and returns True.
|
| 98 |
+
"""
|
| 99 |
+
if (not self._locked and (self._waiters is None or
|
| 100 |
+
all(w.cancelled() for w in self._waiters))):
|
| 101 |
+
self._locked = True
|
| 102 |
+
return True
|
| 103 |
+
|
| 104 |
+
if self._waiters is None:
|
| 105 |
+
self._waiters = collections.deque()
|
| 106 |
+
fut = self._get_loop().create_future()
|
| 107 |
+
self._waiters.append(fut)
|
| 108 |
+
|
| 109 |
+
# Finally block should be called before the CancelledError
|
| 110 |
+
# handling as we don't want CancelledError to call
|
| 111 |
+
# _wake_up_first() and attempt to wake up itself.
|
| 112 |
+
try:
|
| 113 |
+
try:
|
| 114 |
+
await fut
|
| 115 |
+
finally:
|
| 116 |
+
self._waiters.remove(fut)
|
| 117 |
+
except exceptions.CancelledError:
|
| 118 |
+
if not self._locked:
|
| 119 |
+
self._wake_up_first()
|
| 120 |
+
raise
|
| 121 |
+
|
| 122 |
+
self._locked = True
|
| 123 |
+
return True
|
| 124 |
+
|
| 125 |
+
def release(self):
|
| 126 |
+
"""Release a lock.
|
| 127 |
+
|
| 128 |
+
When the lock is locked, reset it to unlocked, and return.
|
| 129 |
+
If any other coroutines are blocked waiting for the lock to become
|
| 130 |
+
unlocked, allow exactly one of them to proceed.
|
| 131 |
+
|
| 132 |
+
When invoked on an unlocked lock, a RuntimeError is raised.
|
| 133 |
+
|
| 134 |
+
There is no return value.
|
| 135 |
+
"""
|
| 136 |
+
if self._locked:
|
| 137 |
+
self._locked = False
|
| 138 |
+
self._wake_up_first()
|
| 139 |
+
else:
|
| 140 |
+
raise RuntimeError('Lock is not acquired.')
|
| 141 |
+
|
| 142 |
+
def _wake_up_first(self):
|
| 143 |
+
"""Wake up the first waiter if it isn't done."""
|
| 144 |
+
if not self._waiters:
|
| 145 |
+
return
|
| 146 |
+
try:
|
| 147 |
+
fut = next(iter(self._waiters))
|
| 148 |
+
except StopIteration:
|
| 149 |
+
return
|
| 150 |
+
|
| 151 |
+
# .done() necessarily means that a waiter will wake up later on and
|
| 152 |
+
# either take the lock, or, if it was cancelled and lock wasn't
|
| 153 |
+
# taken already, will hit this again and wake up a new waiter.
|
| 154 |
+
if not fut.done():
|
| 155 |
+
fut.set_result(True)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class Event(mixins._LoopBoundMixin):
|
| 159 |
+
"""Asynchronous equivalent to threading.Event.
|
| 160 |
+
|
| 161 |
+
Class implementing event objects. An event manages a flag that can be set
|
| 162 |
+
to true with the set() method and reset to false with the clear() method.
|
| 163 |
+
The wait() method blocks until the flag is true. The flag is initially
|
| 164 |
+
false.
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
def __init__(self, *, loop=mixins._marker):
|
| 168 |
+
super().__init__(loop=loop)
|
| 169 |
+
self._waiters = collections.deque()
|
| 170 |
+
self._value = False
|
| 171 |
+
|
| 172 |
+
def __repr__(self):
|
| 173 |
+
res = super().__repr__()
|
| 174 |
+
extra = 'set' if self._value else 'unset'
|
| 175 |
+
if self._waiters:
|
| 176 |
+
extra = f'{extra}, waiters:{len(self._waiters)}'
|
| 177 |
+
return f'<{res[1:-1]} [{extra}]>'
|
| 178 |
+
|
| 179 |
+
def is_set(self):
|
| 180 |
+
"""Return True if and only if the internal flag is true."""
|
| 181 |
+
return self._value
|
| 182 |
+
|
| 183 |
+
def set(self):
|
| 184 |
+
"""Set the internal flag to true. All coroutines waiting for it to
|
| 185 |
+
become true are awakened. Coroutine that call wait() once the flag is
|
| 186 |
+
true will not block at all.
|
| 187 |
+
"""
|
| 188 |
+
if not self._value:
|
| 189 |
+
self._value = True
|
| 190 |
+
|
| 191 |
+
for fut in self._waiters:
|
| 192 |
+
if not fut.done():
|
| 193 |
+
fut.set_result(True)
|
| 194 |
+
|
| 195 |
+
def clear(self):
|
| 196 |
+
"""Reset the internal flag to false. Subsequently, coroutines calling
|
| 197 |
+
wait() will block until set() is called to set the internal flag
|
| 198 |
+
to true again."""
|
| 199 |
+
self._value = False
|
| 200 |
+
|
| 201 |
+
async def wait(self):
|
| 202 |
+
"""Block until the internal flag is true.
|
| 203 |
+
|
| 204 |
+
If the internal flag is true on entry, return True
|
| 205 |
+
immediately. Otherwise, block until another coroutine calls
|
| 206 |
+
set() to set the flag to true, then return True.
|
| 207 |
+
"""
|
| 208 |
+
if self._value:
|
| 209 |
+
return True
|
| 210 |
+
|
| 211 |
+
fut = self._get_loop().create_future()
|
| 212 |
+
self._waiters.append(fut)
|
| 213 |
+
try:
|
| 214 |
+
await fut
|
| 215 |
+
return True
|
| 216 |
+
finally:
|
| 217 |
+
self._waiters.remove(fut)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class Condition(_ContextManagerMixin, mixins._LoopBoundMixin):
|
| 221 |
+
"""Asynchronous equivalent to threading.Condition.
|
| 222 |
+
|
| 223 |
+
This class implements condition variable objects. A condition variable
|
| 224 |
+
allows one or more coroutines to wait until they are notified by another
|
| 225 |
+
coroutine.
|
| 226 |
+
|
| 227 |
+
A new Lock object is created and used as the underlying lock.
|
| 228 |
+
"""
|
| 229 |
+
|
| 230 |
+
def __init__(self, lock=None, *, loop=mixins._marker):
|
| 231 |
+
super().__init__(loop=loop)
|
| 232 |
+
if lock is None:
|
| 233 |
+
lock = Lock()
|
| 234 |
+
|
| 235 |
+
self._lock = lock
|
| 236 |
+
# Export the lock's locked(), acquire() and release() methods.
|
| 237 |
+
self.locked = lock.locked
|
| 238 |
+
self.acquire = lock.acquire
|
| 239 |
+
self.release = lock.release
|
| 240 |
+
|
| 241 |
+
self._waiters = collections.deque()
|
| 242 |
+
|
| 243 |
+
def __repr__(self):
|
| 244 |
+
res = super().__repr__()
|
| 245 |
+
extra = 'locked' if self.locked() else 'unlocked'
|
| 246 |
+
if self._waiters:
|
| 247 |
+
extra = f'{extra}, waiters:{len(self._waiters)}'
|
| 248 |
+
return f'<{res[1:-1]} [{extra}]>'
|
| 249 |
+
|
| 250 |
+
async def wait(self):
|
| 251 |
+
"""Wait until notified.
|
| 252 |
+
|
| 253 |
+
If the calling coroutine has not acquired the lock when this
|
| 254 |
+
method is called, a RuntimeError is raised.
|
| 255 |
+
|
| 256 |
+
This method releases the underlying lock, and then blocks
|
| 257 |
+
until it is awakened by a notify() or notify_all() call for
|
| 258 |
+
the same condition variable in another coroutine. Once
|
| 259 |
+
awakened, it re-acquires the lock and returns True.
|
| 260 |
+
"""
|
| 261 |
+
if not self.locked():
|
| 262 |
+
raise RuntimeError('cannot wait on un-acquired lock')
|
| 263 |
+
|
| 264 |
+
self.release()
|
| 265 |
+
try:
|
| 266 |
+
fut = self._get_loop().create_future()
|
| 267 |
+
self._waiters.append(fut)
|
| 268 |
+
try:
|
| 269 |
+
await fut
|
| 270 |
+
return True
|
| 271 |
+
finally:
|
| 272 |
+
self._waiters.remove(fut)
|
| 273 |
+
|
| 274 |
+
finally:
|
| 275 |
+
# Must reacquire lock even if wait is cancelled
|
| 276 |
+
cancelled = False
|
| 277 |
+
while True:
|
| 278 |
+
try:
|
| 279 |
+
await self.acquire()
|
| 280 |
+
break
|
| 281 |
+
except exceptions.CancelledError:
|
| 282 |
+
cancelled = True
|
| 283 |
+
|
| 284 |
+
if cancelled:
|
| 285 |
+
raise exceptions.CancelledError
|
| 286 |
+
|
| 287 |
+
async def wait_for(self, predicate):
|
| 288 |
+
"""Wait until a predicate becomes true.
|
| 289 |
+
|
| 290 |
+
The predicate should be a callable which result will be
|
| 291 |
+
interpreted as a boolean value. The final predicate value is
|
| 292 |
+
the return value.
|
| 293 |
+
"""
|
| 294 |
+
result = predicate()
|
| 295 |
+
while not result:
|
| 296 |
+
await self.wait()
|
| 297 |
+
result = predicate()
|
| 298 |
+
return result
|
| 299 |
+
|
| 300 |
+
def notify(self, n=1):
|
| 301 |
+
"""By default, wake up one coroutine waiting on this condition, if any.
|
| 302 |
+
If the calling coroutine has not acquired the lock when this method
|
| 303 |
+
is called, a RuntimeError is raised.
|
| 304 |
+
|
| 305 |
+
This method wakes up at most n of the coroutines waiting for the
|
| 306 |
+
condition variable; it is a no-op if no coroutines are waiting.
|
| 307 |
+
|
| 308 |
+
Note: an awakened coroutine does not actually return from its
|
| 309 |
+
wait() call until it can reacquire the lock. Since notify() does
|
| 310 |
+
not release the lock, its caller should.
|
| 311 |
+
"""
|
| 312 |
+
if not self.locked():
|
| 313 |
+
raise RuntimeError('cannot notify on un-acquired lock')
|
| 314 |
+
|
| 315 |
+
idx = 0
|
| 316 |
+
for fut in self._waiters:
|
| 317 |
+
if idx >= n:
|
| 318 |
+
break
|
| 319 |
+
|
| 320 |
+
if not fut.done():
|
| 321 |
+
idx += 1
|
| 322 |
+
fut.set_result(False)
|
| 323 |
+
|
| 324 |
+
def notify_all(self):
|
| 325 |
+
"""Wake up all threads waiting on this condition. This method acts
|
| 326 |
+
like notify(), but wakes up all waiting threads instead of one. If the
|
| 327 |
+
calling thread has not acquired the lock when this method is called,
|
| 328 |
+
a RuntimeError is raised.
|
| 329 |
+
"""
|
| 330 |
+
self.notify(len(self._waiters))
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
class Semaphore(_ContextManagerMixin, mixins._LoopBoundMixin):
|
| 334 |
+
"""A Semaphore implementation.
|
| 335 |
+
|
| 336 |
+
A semaphore manages an internal counter which is decremented by each
|
| 337 |
+
acquire() call and incremented by each release() call. The counter
|
| 338 |
+
can never go below zero; when acquire() finds that it is zero, it blocks,
|
| 339 |
+
waiting until some other thread calls release().
|
| 340 |
+
|
| 341 |
+
Semaphores also support the context management protocol.
|
| 342 |
+
|
| 343 |
+
The optional argument gives the initial value for the internal
|
| 344 |
+
counter; it defaults to 1. If the value given is less than 0,
|
| 345 |
+
ValueError is raised.
|
| 346 |
+
"""
|
| 347 |
+
|
| 348 |
+
def __init__(self, value=1, *, loop=mixins._marker):
|
| 349 |
+
super().__init__(loop=loop)
|
| 350 |
+
if value < 0:
|
| 351 |
+
raise ValueError("Semaphore initial value must be >= 0")
|
| 352 |
+
self._waiters = None
|
| 353 |
+
self._value = value
|
| 354 |
+
|
| 355 |
+
def __repr__(self):
|
| 356 |
+
res = super().__repr__()
|
| 357 |
+
extra = 'locked' if self.locked() else f'unlocked, value:{self._value}'
|
| 358 |
+
if self._waiters:
|
| 359 |
+
extra = f'{extra}, waiters:{len(self._waiters)}'
|
| 360 |
+
return f'<{res[1:-1]} [{extra}]>'
|
| 361 |
+
|
| 362 |
+
def locked(self):
|
| 363 |
+
"""Returns True if semaphore cannot be acquired immediately."""
|
| 364 |
+
return self._value == 0 or (
|
| 365 |
+
any(not w.cancelled() for w in (self._waiters or ())))
|
| 366 |
+
|
| 367 |
+
async def acquire(self):
|
| 368 |
+
"""Acquire a semaphore.
|
| 369 |
+
|
| 370 |
+
If the internal counter is larger than zero on entry,
|
| 371 |
+
decrement it by one and return True immediately. If it is
|
| 372 |
+
zero on entry, block, waiting until some other coroutine has
|
| 373 |
+
called release() to make it larger than 0, and then return
|
| 374 |
+
True.
|
| 375 |
+
"""
|
| 376 |
+
if not self.locked():
|
| 377 |
+
self._value -= 1
|
| 378 |
+
return True
|
| 379 |
+
|
| 380 |
+
if self._waiters is None:
|
| 381 |
+
self._waiters = collections.deque()
|
| 382 |
+
fut = self._get_loop().create_future()
|
| 383 |
+
self._waiters.append(fut)
|
| 384 |
+
|
| 385 |
+
# Finally block should be called before the CancelledError
|
| 386 |
+
# handling as we don't want CancelledError to call
|
| 387 |
+
# _wake_up_first() and attempt to wake up itself.
|
| 388 |
+
try:
|
| 389 |
+
try:
|
| 390 |
+
await fut
|
| 391 |
+
finally:
|
| 392 |
+
self._waiters.remove(fut)
|
| 393 |
+
except exceptions.CancelledError:
|
| 394 |
+
if not fut.cancelled():
|
| 395 |
+
self._value += 1
|
| 396 |
+
self._wake_up_next()
|
| 397 |
+
raise
|
| 398 |
+
|
| 399 |
+
if self._value > 0:
|
| 400 |
+
self._wake_up_next()
|
| 401 |
+
return True
|
| 402 |
+
|
| 403 |
+
def release(self):
|
| 404 |
+
"""Release a semaphore, incrementing the internal counter by one.
|
| 405 |
+
|
| 406 |
+
When it was zero on entry and another coroutine is waiting for it to
|
| 407 |
+
become larger than zero again, wake up that coroutine.
|
| 408 |
+
"""
|
| 409 |
+
self._value += 1
|
| 410 |
+
self._wake_up_next()
|
| 411 |
+
|
| 412 |
+
def _wake_up_next(self):
|
| 413 |
+
"""Wake up the first waiter that isn't done."""
|
| 414 |
+
if not self._waiters:
|
| 415 |
+
return
|
| 416 |
+
|
| 417 |
+
for fut in self._waiters:
|
| 418 |
+
if not fut.done():
|
| 419 |
+
self._value -= 1
|
| 420 |
+
fut.set_result(True)
|
| 421 |
+
return
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
class BoundedSemaphore(Semaphore):
|
| 425 |
+
"""A bounded semaphore implementation.
|
| 426 |
+
|
| 427 |
+
This raises ValueError in release() if it would increase the value
|
| 428 |
+
above the initial value.
|
| 429 |
+
"""
|
| 430 |
+
|
| 431 |
+
def __init__(self, value=1, *, loop=mixins._marker):
|
| 432 |
+
self._bound_value = value
|
| 433 |
+
super().__init__(value, loop=loop)
|
| 434 |
+
|
| 435 |
+
def release(self):
|
| 436 |
+
if self._value >= self._bound_value:
|
| 437 |
+
raise ValueError('BoundedSemaphore released too many times')
|
| 438 |
+
super().release()
|
janus/lib/python3.10/asyncio/mixins.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Event loop mixins."""
|
| 2 |
+
|
| 3 |
+
import threading
|
| 4 |
+
from . import events
|
| 5 |
+
|
| 6 |
+
_global_lock = threading.Lock()
|
| 7 |
+
|
| 8 |
+
# Used as a sentinel for loop parameter
|
| 9 |
+
_marker = object()
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class _LoopBoundMixin:
|
| 13 |
+
_loop = None
|
| 14 |
+
|
| 15 |
+
def __init__(self, *, loop=_marker):
|
| 16 |
+
if loop is not _marker:
|
| 17 |
+
raise TypeError(
|
| 18 |
+
f'As of 3.10, the *loop* parameter was removed from '
|
| 19 |
+
f'{type(self).__name__}() since it is no longer necessary'
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
def _get_loop(self):
|
| 23 |
+
loop = events._get_running_loop()
|
| 24 |
+
|
| 25 |
+
if self._loop is None:
|
| 26 |
+
with _global_lock:
|
| 27 |
+
if self._loop is None:
|
| 28 |
+
self._loop = loop
|
| 29 |
+
if loop is not self._loop:
|
| 30 |
+
raise RuntimeError(f'{self!r} is bound to a different event loop')
|
| 31 |
+
return loop
|
janus/lib/python3.10/asyncio/protocols.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 8 |
+
|
| 9 |
+
class BaseProtocol:
|
| 10 |
+
"""Common base class for protocol interfaces.
|
| 11 |
+
|
| 12 |
+
Usually user implements protocols that derived from BaseProtocol
|
| 13 |
+
like Protocol or ProcessProtocol.
|
| 14 |
+
|
| 15 |
+
The only case when BaseProtocol should be implemented directly is
|
| 16 |
+
write-only transport like write pipe
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
__slots__ = ()
|
| 20 |
+
|
| 21 |
+
def connection_made(self, transport):
|
| 22 |
+
"""Called when a connection is made.
|
| 23 |
+
|
| 24 |
+
The argument is the transport representing the pipe connection.
|
| 25 |
+
To receive data, wait for data_received() calls.
|
| 26 |
+
When the connection is closed, connection_lost() is called.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def connection_lost(self, exc):
|
| 30 |
+
"""Called when the connection is lost or closed.
|
| 31 |
+
|
| 32 |
+
The argument is an exception object or None (the latter
|
| 33 |
+
meaning a regular EOF is received or the connection was
|
| 34 |
+
aborted or closed).
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def pause_writing(self):
|
| 38 |
+
"""Called when the transport's buffer goes over the high-water mark.
|
| 39 |
+
|
| 40 |
+
Pause and resume calls are paired -- pause_writing() is called
|
| 41 |
+
once when the buffer goes strictly over the high-water mark
|
| 42 |
+
(even if subsequent writes increases the buffer size even
|
| 43 |
+
more), and eventually resume_writing() is called once when the
|
| 44 |
+
buffer size reaches the low-water mark.
|
| 45 |
+
|
| 46 |
+
Note that if the buffer size equals the high-water mark,
|
| 47 |
+
pause_writing() is not called -- it must go strictly over.
|
| 48 |
+
Conversely, resume_writing() is called when the buffer size is
|
| 49 |
+
equal or lower than the low-water mark. These end conditions
|
| 50 |
+
are important to ensure that things go as expected when either
|
| 51 |
+
mark is zero.
|
| 52 |
+
|
| 53 |
+
NOTE: This is the only Protocol callback that is not called
|
| 54 |
+
through EventLoop.call_soon() -- if it were, it would have no
|
| 55 |
+
effect when it's most needed (when the app keeps writing
|
| 56 |
+
without yielding until pause_writing() is called).
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def resume_writing(self):
|
| 60 |
+
"""Called when the transport's buffer drains below the low-water mark.
|
| 61 |
+
|
| 62 |
+
See pause_writing() for details.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class Protocol(BaseProtocol):
|
| 67 |
+
"""Interface for stream protocol.
|
| 68 |
+
|
| 69 |
+
The user should implement this interface. They can inherit from
|
| 70 |
+
this class but don't need to. The implementations here do
|
| 71 |
+
nothing (they don't raise exceptions).
|
| 72 |
+
|
| 73 |
+
When the user wants to requests a transport, they pass a protocol
|
| 74 |
+
factory to a utility function (e.g., EventLoop.create_connection()).
|
| 75 |
+
|
| 76 |
+
When the connection is made successfully, connection_made() is
|
| 77 |
+
called with a suitable transport object. Then data_received()
|
| 78 |
+
will be called 0 or more times with data (bytes) received from the
|
| 79 |
+
transport; finally, connection_lost() will be called exactly once
|
| 80 |
+
with either an exception object or None as an argument.
|
| 81 |
+
|
| 82 |
+
State machine of calls:
|
| 83 |
+
|
| 84 |
+
start -> CM [-> DR*] [-> ER?] -> CL -> end
|
| 85 |
+
|
| 86 |
+
* CM: connection_made()
|
| 87 |
+
* DR: data_received()
|
| 88 |
+
* ER: eof_received()
|
| 89 |
+
* CL: connection_lost()
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
__slots__ = ()
|
| 93 |
+
|
| 94 |
+
def data_received(self, data):
|
| 95 |
+
"""Called when some data is received.
|
| 96 |
+
|
| 97 |
+
The argument is a bytes object.
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
def eof_received(self):
|
| 101 |
+
"""Called when the other end calls write_eof() or equivalent.
|
| 102 |
+
|
| 103 |
+
If this returns a false value (including None), the transport
|
| 104 |
+
will close itself. If it returns a true value, closing the
|
| 105 |
+
transport is up to the protocol.
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class BufferedProtocol(BaseProtocol):
|
| 110 |
+
"""Interface for stream protocol with manual buffer control.
|
| 111 |
+
|
| 112 |
+
Event methods, such as `create_server` and `create_connection`,
|
| 113 |
+
accept factories that return protocols that implement this interface.
|
| 114 |
+
|
| 115 |
+
The idea of BufferedProtocol is that it allows to manually allocate
|
| 116 |
+
and control the receive buffer. Event loops can then use the buffer
|
| 117 |
+
provided by the protocol to avoid unnecessary data copies. This
|
| 118 |
+
can result in noticeable performance improvement for protocols that
|
| 119 |
+
receive big amounts of data. Sophisticated protocols can allocate
|
| 120 |
+
the buffer only once at creation time.
|
| 121 |
+
|
| 122 |
+
State machine of calls:
|
| 123 |
+
|
| 124 |
+
start -> CM [-> GB [-> BU?]]* [-> ER?] -> CL -> end
|
| 125 |
+
|
| 126 |
+
* CM: connection_made()
|
| 127 |
+
* GB: get_buffer()
|
| 128 |
+
* BU: buffer_updated()
|
| 129 |
+
* ER: eof_received()
|
| 130 |
+
* CL: connection_lost()
|
| 131 |
+
"""
|
| 132 |
+
|
| 133 |
+
__slots__ = ()
|
| 134 |
+
|
| 135 |
+
def get_buffer(self, sizehint):
|
| 136 |
+
"""Called to allocate a new receive buffer.
|
| 137 |
+
|
| 138 |
+
*sizehint* is a recommended minimal size for the returned
|
| 139 |
+
buffer. When set to -1, the buffer size can be arbitrary.
|
| 140 |
+
|
| 141 |
+
Must return an object that implements the
|
| 142 |
+
:ref:`buffer protocol <bufferobjects>`.
|
| 143 |
+
It is an error to return a zero-sized buffer.
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
def buffer_updated(self, nbytes):
|
| 147 |
+
"""Called when the buffer was updated with the received data.
|
| 148 |
+
|
| 149 |
+
*nbytes* is the total number of bytes that were written to
|
| 150 |
+
the buffer.
|
| 151 |
+
"""
|
| 152 |
+
|
| 153 |
+
def eof_received(self):
|
| 154 |
+
"""Called when the other end calls write_eof() or equivalent.
|
| 155 |
+
|
| 156 |
+
If this returns a false value (including None), the transport
|
| 157 |
+
will close itself. If it returns a true value, closing the
|
| 158 |
+
transport is up to the protocol.
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class DatagramProtocol(BaseProtocol):
|
| 163 |
+
"""Interface for datagram protocol."""
|
| 164 |
+
|
| 165 |
+
__slots__ = ()
|
| 166 |
+
|
| 167 |
+
def datagram_received(self, data, addr):
|
| 168 |
+
"""Called when some datagram is received."""
|
| 169 |
+
|
| 170 |
+
def error_received(self, exc):
|
| 171 |
+
"""Called when a send or receive operation raises an OSError.
|
| 172 |
+
|
| 173 |
+
(Other than BlockingIOError or InterruptedError.)
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class SubprocessProtocol(BaseProtocol):
|
| 178 |
+
"""Interface for protocol for subprocess calls."""
|
| 179 |
+
|
| 180 |
+
__slots__ = ()
|
| 181 |
+
|
| 182 |
+
def pipe_data_received(self, fd, data):
|
| 183 |
+
"""Called when the subprocess writes data into stdout/stderr pipe.
|
| 184 |
+
|
| 185 |
+
fd is int file descriptor.
|
| 186 |
+
data is bytes object.
|
| 187 |
+
"""
|
| 188 |
+
|
| 189 |
+
def pipe_connection_lost(self, fd, exc):
|
| 190 |
+
"""Called when a file descriptor associated with the child process is
|
| 191 |
+
closed.
|
| 192 |
+
|
| 193 |
+
fd is the int file descriptor that was closed.
|
| 194 |
+
"""
|
| 195 |
+
|
| 196 |
+
def process_exited(self):
|
| 197 |
+
"""Called when subprocess has exited."""
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def _feed_data_to_buffered_proto(proto, data):
|
| 201 |
+
data_len = len(data)
|
| 202 |
+
while data_len:
|
| 203 |
+
buf = proto.get_buffer(data_len)
|
| 204 |
+
buf_len = len(buf)
|
| 205 |
+
if not buf_len:
|
| 206 |
+
raise RuntimeError('get_buffer() returned an empty buffer')
|
| 207 |
+
|
| 208 |
+
if buf_len >= data_len:
|
| 209 |
+
buf[:data_len] = data
|
| 210 |
+
proto.buffer_updated(data_len)
|
| 211 |
+
return
|
| 212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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Event loop using a selector and related classes.
|
| 2 |
+
|
| 3 |
+
A selector is a "notify-when-ready" multiplexer. For a subclass which
|
| 4 |
+
also includes support for signal handling, see the unix_events sub-module.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
__all__ = 'BaseSelectorEventLoop',
|
| 8 |
+
|
| 9 |
+
import collections
|
| 10 |
+
import errno
|
| 11 |
+
import functools
|
| 12 |
+
import selectors
|
| 13 |
+
import socket
|
| 14 |
+
import warnings
|
| 15 |
+
import weakref
|
| 16 |
+
try:
|
| 17 |
+
import ssl
|
| 18 |
+
except ImportError: # pragma: no cover
|
| 19 |
+
ssl = None
|
| 20 |
+
|
| 21 |
+
from . import base_events
|
| 22 |
+
from . import constants
|
| 23 |
+
from . import events
|
| 24 |
+
from . import futures
|
| 25 |
+
from . import protocols
|
| 26 |
+
from . import sslproto
|
| 27 |
+
from . import transports
|
| 28 |
+
from . import trsock
|
| 29 |
+
from .log import logger
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _test_selector_event(selector, fd, event):
|
| 33 |
+
# Test if the selector is monitoring 'event' events
|
| 34 |
+
# for the file descriptor 'fd'.
|
| 35 |
+
try:
|
| 36 |
+
key = selector.get_key(fd)
|
| 37 |
+
except KeyError:
|
| 38 |
+
return False
|
| 39 |
+
else:
|
| 40 |
+
return bool(key.events & event)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class BaseSelectorEventLoop(base_events.BaseEventLoop):
|
| 44 |
+
"""Selector event loop.
|
| 45 |
+
|
| 46 |
+
See events.EventLoop for API specification.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
def __init__(self, selector=None):
|
| 50 |
+
super().__init__()
|
| 51 |
+
|
| 52 |
+
if selector is None:
|
| 53 |
+
selector = selectors.DefaultSelector()
|
| 54 |
+
logger.debug('Using selector: %s', selector.__class__.__name__)
|
| 55 |
+
self._selector = selector
|
| 56 |
+
self._make_self_pipe()
|
| 57 |
+
self._transports = weakref.WeakValueDictionary()
|
| 58 |
+
|
| 59 |
+
def _make_socket_transport(self, sock, protocol, waiter=None, *,
|
| 60 |
+
extra=None, server=None):
|
| 61 |
+
return _SelectorSocketTransport(self, sock, protocol, waiter,
|
| 62 |
+
extra, server)
|
| 63 |
+
|
| 64 |
+
def _make_ssl_transport(
|
| 65 |
+
self, rawsock, protocol, sslcontext, waiter=None,
|
| 66 |
+
*, server_side=False, server_hostname=None,
|
| 67 |
+
extra=None, server=None,
|
| 68 |
+
ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT):
|
| 69 |
+
ssl_protocol = sslproto.SSLProtocol(
|
| 70 |
+
self, protocol, sslcontext, waiter,
|
| 71 |
+
server_side, server_hostname,
|
| 72 |
+
ssl_handshake_timeout=ssl_handshake_timeout)
|
| 73 |
+
_SelectorSocketTransport(self, rawsock, ssl_protocol,
|
| 74 |
+
extra=extra, server=server)
|
| 75 |
+
return ssl_protocol._app_transport
|
| 76 |
+
|
| 77 |
+
def _make_datagram_transport(self, sock, protocol,
|
| 78 |
+
address=None, waiter=None, extra=None):
|
| 79 |
+
return _SelectorDatagramTransport(self, sock, protocol,
|
| 80 |
+
address, waiter, extra)
|
| 81 |
+
|
| 82 |
+
def close(self):
|
| 83 |
+
if self.is_running():
|
| 84 |
+
raise RuntimeError("Cannot close a running event loop")
|
| 85 |
+
if self.is_closed():
|
| 86 |
+
return
|
| 87 |
+
self._close_self_pipe()
|
| 88 |
+
super().close()
|
| 89 |
+
if self._selector is not None:
|
| 90 |
+
self._selector.close()
|
| 91 |
+
self._selector = None
|
| 92 |
+
|
| 93 |
+
def _close_self_pipe(self):
|
| 94 |
+
self._remove_reader(self._ssock.fileno())
|
| 95 |
+
self._ssock.close()
|
| 96 |
+
self._ssock = None
|
| 97 |
+
self._csock.close()
|
| 98 |
+
self._csock = None
|
| 99 |
+
self._internal_fds -= 1
|
| 100 |
+
|
| 101 |
+
def _make_self_pipe(self):
|
| 102 |
+
# A self-socket, really. :-)
|
| 103 |
+
self._ssock, self._csock = socket.socketpair()
|
| 104 |
+
self._ssock.setblocking(False)
|
| 105 |
+
self._csock.setblocking(False)
|
| 106 |
+
self._internal_fds += 1
|
| 107 |
+
self._add_reader(self._ssock.fileno(), self._read_from_self)
|
| 108 |
+
|
| 109 |
+
def _process_self_data(self, data):
|
| 110 |
+
pass
|
| 111 |
+
|
| 112 |
+
def _read_from_self(self):
|
| 113 |
+
while True:
|
| 114 |
+
try:
|
| 115 |
+
data = self._ssock.recv(4096)
|
| 116 |
+
if not data:
|
| 117 |
+
break
|
| 118 |
+
self._process_self_data(data)
|
| 119 |
+
except InterruptedError:
|
| 120 |
+
continue
|
| 121 |
+
except BlockingIOError:
|
| 122 |
+
break
|
| 123 |
+
|
| 124 |
+
def _write_to_self(self):
|
| 125 |
+
# This may be called from a different thread, possibly after
|
| 126 |
+
# _close_self_pipe() has been called or even while it is
|
| 127 |
+
# running. Guard for self._csock being None or closed. When
|
| 128 |
+
# a socket is closed, send() raises OSError (with errno set to
|
| 129 |
+
# EBADF, but let's not rely on the exact error code).
|
| 130 |
+
csock = self._csock
|
| 131 |
+
if csock is None:
|
| 132 |
+
return
|
| 133 |
+
|
| 134 |
+
try:
|
| 135 |
+
csock.send(b'\0')
|
| 136 |
+
except OSError:
|
| 137 |
+
if self._debug:
|
| 138 |
+
logger.debug("Fail to write a null byte into the "
|
| 139 |
+
"self-pipe socket",
|
| 140 |
+
exc_info=True)
|
| 141 |
+
|
| 142 |
+
def _start_serving(self, protocol_factory, sock,
|
| 143 |
+
sslcontext=None, server=None, backlog=100,
|
| 144 |
+
ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT):
|
| 145 |
+
self._add_reader(sock.fileno(), self._accept_connection,
|
| 146 |
+
protocol_factory, sock, sslcontext, server, backlog,
|
| 147 |
+
ssl_handshake_timeout)
|
| 148 |
+
|
| 149 |
+
def _accept_connection(
|
| 150 |
+
self, protocol_factory, sock,
|
| 151 |
+
sslcontext=None, server=None, backlog=100,
|
| 152 |
+
ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT):
|
| 153 |
+
# This method is only called once for each event loop tick where the
|
| 154 |
+
# listening socket has triggered an EVENT_READ. There may be multiple
|
| 155 |
+
# connections waiting for an .accept() so it is called in a loop.
|
| 156 |
+
# See https://bugs.python.org/issue27906 for more details.
|
| 157 |
+
for _ in range(backlog):
|
| 158 |
+
try:
|
| 159 |
+
conn, addr = sock.accept()
|
| 160 |
+
if self._debug:
|
| 161 |
+
logger.debug("%r got a new connection from %r: %r",
|
| 162 |
+
server, addr, conn)
|
| 163 |
+
conn.setblocking(False)
|
| 164 |
+
except (BlockingIOError, InterruptedError, ConnectionAbortedError):
|
| 165 |
+
# Early exit because the socket accept buffer is empty.
|
| 166 |
+
return None
|
| 167 |
+
except OSError as exc:
|
| 168 |
+
# There's nowhere to send the error, so just log it.
|
| 169 |
+
if exc.errno in (errno.EMFILE, errno.ENFILE,
|
| 170 |
+
errno.ENOBUFS, errno.ENOMEM):
|
| 171 |
+
# Some platforms (e.g. Linux keep reporting the FD as
|
| 172 |
+
# ready, so we remove the read handler temporarily.
|
| 173 |
+
# We'll try again in a while.
|
| 174 |
+
self.call_exception_handler({
|
| 175 |
+
'message': 'socket.accept() out of system resource',
|
| 176 |
+
'exception': exc,
|
| 177 |
+
'socket': trsock.TransportSocket(sock),
|
| 178 |
+
})
|
| 179 |
+
self._remove_reader(sock.fileno())
|
| 180 |
+
self.call_later(constants.ACCEPT_RETRY_DELAY,
|
| 181 |
+
self._start_serving,
|
| 182 |
+
protocol_factory, sock, sslcontext, server,
|
| 183 |
+
backlog, ssl_handshake_timeout)
|
| 184 |
+
else:
|
| 185 |
+
raise # The event loop will catch, log and ignore it.
|
| 186 |
+
else:
|
| 187 |
+
extra = {'peername': addr}
|
| 188 |
+
accept = self._accept_connection2(
|
| 189 |
+
protocol_factory, conn, extra, sslcontext, server,
|
| 190 |
+
ssl_handshake_timeout)
|
| 191 |
+
self.create_task(accept)
|
| 192 |
+
|
| 193 |
+
async def _accept_connection2(
|
| 194 |
+
self, protocol_factory, conn, extra,
|
| 195 |
+
sslcontext=None, server=None,
|
| 196 |
+
ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT):
|
| 197 |
+
protocol = None
|
| 198 |
+
transport = None
|
| 199 |
+
try:
|
| 200 |
+
protocol = protocol_factory()
|
| 201 |
+
waiter = self.create_future()
|
| 202 |
+
if sslcontext:
|
| 203 |
+
transport = self._make_ssl_transport(
|
| 204 |
+
conn, protocol, sslcontext, waiter=waiter,
|
| 205 |
+
server_side=True, extra=extra, server=server,
|
| 206 |
+
ssl_handshake_timeout=ssl_handshake_timeout)
|
| 207 |
+
else:
|
| 208 |
+
transport = self._make_socket_transport(
|
| 209 |
+
conn, protocol, waiter=waiter, extra=extra,
|
| 210 |
+
server=server)
|
| 211 |
+
|
| 212 |
+
try:
|
| 213 |
+
await waiter
|
| 214 |
+
except BaseException:
|
| 215 |
+
transport.close()
|
| 216 |
+
raise
|
| 217 |
+
# It's now up to the protocol to handle the connection.
|
| 218 |
+
|
| 219 |
+
except (SystemExit, KeyboardInterrupt):
|
| 220 |
+
raise
|
| 221 |
+
except BaseException as exc:
|
| 222 |
+
if self._debug:
|
| 223 |
+
context = {
|
| 224 |
+
'message':
|
| 225 |
+
'Error on transport creation for incoming connection',
|
| 226 |
+
'exception': exc,
|
| 227 |
+
}
|
| 228 |
+
if protocol is not None:
|
| 229 |
+
context['protocol'] = protocol
|
| 230 |
+
if transport is not None:
|
| 231 |
+
context['transport'] = transport
|
| 232 |
+
self.call_exception_handler(context)
|
| 233 |
+
|
| 234 |
+
def _ensure_fd_no_transport(self, fd):
|
| 235 |
+
fileno = fd
|
| 236 |
+
if not isinstance(fileno, int):
|
| 237 |
+
try:
|
| 238 |
+
fileno = int(fileno.fileno())
|
| 239 |
+
except (AttributeError, TypeError, ValueError):
|
| 240 |
+
# This code matches selectors._fileobj_to_fd function.
|
| 241 |
+
raise ValueError(f"Invalid file object: {fd!r}") from None
|
| 242 |
+
try:
|
| 243 |
+
transport = self._transports[fileno]
|
| 244 |
+
except KeyError:
|
| 245 |
+
pass
|
| 246 |
+
else:
|
| 247 |
+
if not transport.is_closing():
|
| 248 |
+
raise RuntimeError(
|
| 249 |
+
f'File descriptor {fd!r} is used by transport '
|
| 250 |
+
f'{transport!r}')
|
| 251 |
+
|
| 252 |
+
def _add_reader(self, fd, callback, *args):
|
| 253 |
+
self._check_closed()
|
| 254 |
+
handle = events.Handle(callback, args, self, None)
|
| 255 |
+
try:
|
| 256 |
+
key = self._selector.get_key(fd)
|
| 257 |
+
except KeyError:
|
| 258 |
+
self._selector.register(fd, selectors.EVENT_READ,
|
| 259 |
+
(handle, None))
|
| 260 |
+
else:
|
| 261 |
+
mask, (reader, writer) = key.events, key.data
|
| 262 |
+
self._selector.modify(fd, mask | selectors.EVENT_READ,
|
| 263 |
+
(handle, writer))
|
| 264 |
+
if reader is not None:
|
| 265 |
+
reader.cancel()
|
| 266 |
+
return handle
|
| 267 |
+
|
| 268 |
+
def _remove_reader(self, fd):
|
| 269 |
+
if self.is_closed():
|
| 270 |
+
return False
|
| 271 |
+
try:
|
| 272 |
+
key = self._selector.get_key(fd)
|
| 273 |
+
except KeyError:
|
| 274 |
+
return False
|
| 275 |
+
else:
|
| 276 |
+
mask, (reader, writer) = key.events, key.data
|
| 277 |
+
mask &= ~selectors.EVENT_READ
|
| 278 |
+
if not mask:
|
| 279 |
+
self._selector.unregister(fd)
|
| 280 |
+
else:
|
| 281 |
+
self._selector.modify(fd, mask, (None, writer))
|
| 282 |
+
|
| 283 |
+
if reader is not None:
|
| 284 |
+
reader.cancel()
|
| 285 |
+
return True
|
| 286 |
+
else:
|
| 287 |
+
return False
|
| 288 |
+
|
| 289 |
+
def _add_writer(self, fd, callback, *args):
|
| 290 |
+
self._check_closed()
|
| 291 |
+
handle = events.Handle(callback, args, self, None)
|
| 292 |
+
try:
|
| 293 |
+
key = self._selector.get_key(fd)
|
| 294 |
+
except KeyError:
|
| 295 |
+
self._selector.register(fd, selectors.EVENT_WRITE,
|
| 296 |
+
(None, handle))
|
| 297 |
+
else:
|
| 298 |
+
mask, (reader, writer) = key.events, key.data
|
| 299 |
+
self._selector.modify(fd, mask | selectors.EVENT_WRITE,
|
| 300 |
+
(reader, handle))
|
| 301 |
+
if writer is not None:
|
| 302 |
+
writer.cancel()
|
| 303 |
+
return handle
|
| 304 |
+
|
| 305 |
+
def _remove_writer(self, fd):
|
| 306 |
+
"""Remove a writer callback."""
|
| 307 |
+
if self.is_closed():
|
| 308 |
+
return False
|
| 309 |
+
try:
|
| 310 |
+
key = self._selector.get_key(fd)
|
| 311 |
+
except KeyError:
|
| 312 |
+
return False
|
| 313 |
+
else:
|
| 314 |
+
mask, (reader, writer) = key.events, key.data
|
| 315 |
+
# Remove both writer and connector.
|
| 316 |
+
mask &= ~selectors.EVENT_WRITE
|
| 317 |
+
if not mask:
|
| 318 |
+
self._selector.unregister(fd)
|
| 319 |
+
else:
|
| 320 |
+
self._selector.modify(fd, mask, (reader, None))
|
| 321 |
+
|
| 322 |
+
if writer is not None:
|
| 323 |
+
writer.cancel()
|
| 324 |
+
return True
|
| 325 |
+
else:
|
| 326 |
+
return False
|
| 327 |
+
|
| 328 |
+
def add_reader(self, fd, callback, *args):
|
| 329 |
+
"""Add a reader callback."""
|
| 330 |
+
self._ensure_fd_no_transport(fd)
|
| 331 |
+
self._add_reader(fd, callback, *args)
|
| 332 |
+
|
| 333 |
+
def remove_reader(self, fd):
|
| 334 |
+
"""Remove a reader callback."""
|
| 335 |
+
self._ensure_fd_no_transport(fd)
|
| 336 |
+
return self._remove_reader(fd)
|
| 337 |
+
|
| 338 |
+
def add_writer(self, fd, callback, *args):
|
| 339 |
+
"""Add a writer callback.."""
|
| 340 |
+
self._ensure_fd_no_transport(fd)
|
| 341 |
+
self._add_writer(fd, callback, *args)
|
| 342 |
+
|
| 343 |
+
def remove_writer(self, fd):
|
| 344 |
+
"""Remove a writer callback."""
|
| 345 |
+
self._ensure_fd_no_transport(fd)
|
| 346 |
+
return self._remove_writer(fd)
|
| 347 |
+
|
| 348 |
+
async def sock_recv(self, sock, n):
|
| 349 |
+
"""Receive data from the socket.
|
| 350 |
+
|
| 351 |
+
The return value is a bytes object representing the data received.
|
| 352 |
+
The maximum amount of data to be received at once is specified by
|
| 353 |
+
nbytes.
|
| 354 |
+
"""
|
| 355 |
+
base_events._check_ssl_socket(sock)
|
| 356 |
+
if self._debug and sock.gettimeout() != 0:
|
| 357 |
+
raise ValueError("the socket must be non-blocking")
|
| 358 |
+
try:
|
| 359 |
+
return sock.recv(n)
|
| 360 |
+
except (BlockingIOError, InterruptedError):
|
| 361 |
+
pass
|
| 362 |
+
fut = self.create_future()
|
| 363 |
+
fd = sock.fileno()
|
| 364 |
+
self._ensure_fd_no_transport(fd)
|
| 365 |
+
handle = self._add_reader(fd, self._sock_recv, fut, sock, n)
|
| 366 |
+
fut.add_done_callback(
|
| 367 |
+
functools.partial(self._sock_read_done, fd, handle=handle))
|
| 368 |
+
return await fut
|
| 369 |
+
|
| 370 |
+
def _sock_read_done(self, fd, fut, handle=None):
|
| 371 |
+
if handle is None or not handle.cancelled():
|
| 372 |
+
self.remove_reader(fd)
|
| 373 |
+
|
| 374 |
+
def _sock_recv(self, fut, sock, n):
|
| 375 |
+
# _sock_recv() can add itself as an I/O callback if the operation can't
|
| 376 |
+
# be done immediately. Don't use it directly, call sock_recv().
|
| 377 |
+
if fut.done():
|
| 378 |
+
return
|
| 379 |
+
try:
|
| 380 |
+
data = sock.recv(n)
|
| 381 |
+
except (BlockingIOError, InterruptedError):
|
| 382 |
+
return # try again next time
|
| 383 |
+
except (SystemExit, KeyboardInterrupt):
|
| 384 |
+
raise
|
| 385 |
+
except BaseException as exc:
|
| 386 |
+
fut.set_exception(exc)
|
| 387 |
+
else:
|
| 388 |
+
fut.set_result(data)
|
| 389 |
+
|
| 390 |
+
async def sock_recv_into(self, sock, buf):
|
| 391 |
+
"""Receive data from the socket.
|
| 392 |
+
|
| 393 |
+
The received data is written into *buf* (a writable buffer).
|
| 394 |
+
The return value is the number of bytes written.
|
| 395 |
+
"""
|
| 396 |
+
base_events._check_ssl_socket(sock)
|
| 397 |
+
if self._debug and sock.gettimeout() != 0:
|
| 398 |
+
raise ValueError("the socket must be non-blocking")
|
| 399 |
+
try:
|
| 400 |
+
return sock.recv_into(buf)
|
| 401 |
+
except (BlockingIOError, InterruptedError):
|
| 402 |
+
pass
|
| 403 |
+
fut = self.create_future()
|
| 404 |
+
fd = sock.fileno()
|
| 405 |
+
self._ensure_fd_no_transport(fd)
|
| 406 |
+
handle = self._add_reader(fd, self._sock_recv_into, fut, sock, buf)
|
| 407 |
+
fut.add_done_callback(
|
| 408 |
+
functools.partial(self._sock_read_done, fd, handle=handle))
|
| 409 |
+
return await fut
|
| 410 |
+
|
| 411 |
+
def _sock_recv_into(self, fut, sock, buf):
|
| 412 |
+
# _sock_recv_into() can add itself as an I/O callback if the operation
|
| 413 |
+
# can't be done immediately. Don't use it directly, call
|
| 414 |
+
# sock_recv_into().
|
| 415 |
+
if fut.done():
|
| 416 |
+
return
|
| 417 |
+
try:
|
| 418 |
+
nbytes = sock.recv_into(buf)
|
| 419 |
+
except (BlockingIOError, InterruptedError):
|
| 420 |
+
return # try again next time
|
| 421 |
+
except (SystemExit, KeyboardInterrupt):
|
| 422 |
+
raise
|
| 423 |
+
except BaseException as exc:
|
| 424 |
+
fut.set_exception(exc)
|
| 425 |
+
else:
|
| 426 |
+
fut.set_result(nbytes)
|
| 427 |
+
|
| 428 |
+
async def sock_sendall(self, sock, data):
|
| 429 |
+
"""Send data to the socket.
|
| 430 |
+
|
| 431 |
+
The socket must be connected to a remote socket. This method continues
|
| 432 |
+
to send data from data until either all data has been sent or an
|
| 433 |
+
error occurs. None is returned on success. On error, an exception is
|
| 434 |
+
raised, and there is no way to determine how much data, if any, was
|
| 435 |
+
successfully processed by the receiving end of the connection.
|
| 436 |
+
"""
|
| 437 |
+
base_events._check_ssl_socket(sock)
|
| 438 |
+
if self._debug and sock.gettimeout() != 0:
|
| 439 |
+
raise ValueError("the socket must be non-blocking")
|
| 440 |
+
try:
|
| 441 |
+
n = sock.send(data)
|
| 442 |
+
except (BlockingIOError, InterruptedError):
|
| 443 |
+
n = 0
|
| 444 |
+
|
| 445 |
+
if n == len(data):
|
| 446 |
+
# all data sent
|
| 447 |
+
return
|
| 448 |
+
|
| 449 |
+
fut = self.create_future()
|
| 450 |
+
fd = sock.fileno()
|
| 451 |
+
self._ensure_fd_no_transport(fd)
|
| 452 |
+
# use a trick with a list in closure to store a mutable state
|
| 453 |
+
handle = self._add_writer(fd, self._sock_sendall, fut, sock,
|
| 454 |
+
memoryview(data), [n])
|
| 455 |
+
fut.add_done_callback(
|
| 456 |
+
functools.partial(self._sock_write_done, fd, handle=handle))
|
| 457 |
+
return await fut
|
| 458 |
+
|
| 459 |
+
def _sock_sendall(self, fut, sock, view, pos):
|
| 460 |
+
if fut.done():
|
| 461 |
+
# Future cancellation can be scheduled on previous loop iteration
|
| 462 |
+
return
|
| 463 |
+
start = pos[0]
|
| 464 |
+
try:
|
| 465 |
+
n = sock.send(view[start:])
|
| 466 |
+
except (BlockingIOError, InterruptedError):
|
| 467 |
+
return
|
| 468 |
+
except (SystemExit, KeyboardInterrupt):
|
| 469 |
+
raise
|
| 470 |
+
except BaseException as exc:
|
| 471 |
+
fut.set_exception(exc)
|
| 472 |
+
return
|
| 473 |
+
|
| 474 |
+
start += n
|
| 475 |
+
|
| 476 |
+
if start == len(view):
|
| 477 |
+
fut.set_result(None)
|
| 478 |
+
else:
|
| 479 |
+
pos[0] = start
|
| 480 |
+
|
| 481 |
+
async def sock_connect(self, sock, address):
|
| 482 |
+
"""Connect to a remote socket at address.
|
| 483 |
+
|
| 484 |
+
This method is a coroutine.
|
| 485 |
+
"""
|
| 486 |
+
base_events._check_ssl_socket(sock)
|
| 487 |
+
if self._debug and sock.gettimeout() != 0:
|
| 488 |
+
raise ValueError("the socket must be non-blocking")
|
| 489 |
+
|
| 490 |
+
if sock.family == socket.AF_INET or (
|
| 491 |
+
base_events._HAS_IPv6 and sock.family == socket.AF_INET6):
|
| 492 |
+
resolved = await self._ensure_resolved(
|
| 493 |
+
address, family=sock.family, type=sock.type, proto=sock.proto,
|
| 494 |
+
loop=self,
|
| 495 |
+
)
|
| 496 |
+
_, _, _, _, address = resolved[0]
|
| 497 |
+
|
| 498 |
+
fut = self.create_future()
|
| 499 |
+
self._sock_connect(fut, sock, address)
|
| 500 |
+
try:
|
| 501 |
+
return await fut
|
| 502 |
+
finally:
|
| 503 |
+
# Needed to break cycles when an exception occurs.
|
| 504 |
+
fut = None
|
| 505 |
+
|
| 506 |
+
def _sock_connect(self, fut, sock, address):
|
| 507 |
+
fd = sock.fileno()
|
| 508 |
+
try:
|
| 509 |
+
sock.connect(address)
|
| 510 |
+
except (BlockingIOError, InterruptedError):
|
| 511 |
+
# Issue #23618: When the C function connect() fails with EINTR, the
|
| 512 |
+
# connection runs in background. We have to wait until the socket
|
| 513 |
+
# becomes writable to be notified when the connection succeed or
|
| 514 |
+
# fails.
|
| 515 |
+
self._ensure_fd_no_transport(fd)
|
| 516 |
+
handle = self._add_writer(
|
| 517 |
+
fd, self._sock_connect_cb, fut, sock, address)
|
| 518 |
+
fut.add_done_callback(
|
| 519 |
+
functools.partial(self._sock_write_done, fd, handle=handle))
|
| 520 |
+
except (SystemExit, KeyboardInterrupt):
|
| 521 |
+
raise
|
| 522 |
+
except BaseException as exc:
|
| 523 |
+
fut.set_exception(exc)
|
| 524 |
+
else:
|
| 525 |
+
fut.set_result(None)
|
| 526 |
+
finally:
|
| 527 |
+
fut = None
|
| 528 |
+
|
| 529 |
+
def _sock_write_done(self, fd, fut, handle=None):
|
| 530 |
+
if handle is None or not handle.cancelled():
|
| 531 |
+
self.remove_writer(fd)
|
| 532 |
+
|
| 533 |
+
def _sock_connect_cb(self, fut, sock, address):
|
| 534 |
+
if fut.done():
|
| 535 |
+
return
|
| 536 |
+
|
| 537 |
+
try:
|
| 538 |
+
err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
|
| 539 |
+
if err != 0:
|
| 540 |
+
# Jump to any except clause below.
|
| 541 |
+
raise OSError(err, f'Connect call failed {address}')
|
| 542 |
+
except (BlockingIOError, InterruptedError):
|
| 543 |
+
# socket is still registered, the callback will be retried later
|
| 544 |
+
pass
|
| 545 |
+
except (SystemExit, KeyboardInterrupt):
|
| 546 |
+
raise
|
| 547 |
+
except BaseException as exc:
|
| 548 |
+
fut.set_exception(exc)
|
| 549 |
+
else:
|
| 550 |
+
fut.set_result(None)
|
| 551 |
+
finally:
|
| 552 |
+
fut = None
|
| 553 |
+
|
| 554 |
+
async def sock_accept(self, sock):
|
| 555 |
+
"""Accept a connection.
|
| 556 |
+
|
| 557 |
+
The socket must be bound to an address and listening for connections.
|
| 558 |
+
The return value is a pair (conn, address) where conn is a new socket
|
| 559 |
+
object usable to send and receive data on the connection, and address
|
| 560 |
+
is the address bound to the socket on the other end of the connection.
|
| 561 |
+
"""
|
| 562 |
+
base_events._check_ssl_socket(sock)
|
| 563 |
+
if self._debug and sock.gettimeout() != 0:
|
| 564 |
+
raise ValueError("the socket must be non-blocking")
|
| 565 |
+
fut = self.create_future()
|
| 566 |
+
self._sock_accept(fut, sock)
|
| 567 |
+
return await fut
|
| 568 |
+
|
| 569 |
+
def _sock_accept(self, fut, sock):
|
| 570 |
+
fd = sock.fileno()
|
| 571 |
+
try:
|
| 572 |
+
conn, address = sock.accept()
|
| 573 |
+
conn.setblocking(False)
|
| 574 |
+
except (BlockingIOError, InterruptedError):
|
| 575 |
+
self._ensure_fd_no_transport(fd)
|
| 576 |
+
handle = self._add_reader(fd, self._sock_accept, fut, sock)
|
| 577 |
+
fut.add_done_callback(
|
| 578 |
+
functools.partial(self._sock_read_done, fd, handle=handle))
|
| 579 |
+
except (SystemExit, KeyboardInterrupt):
|
| 580 |
+
raise
|
| 581 |
+
except BaseException as exc:
|
| 582 |
+
fut.set_exception(exc)
|
| 583 |
+
else:
|
| 584 |
+
fut.set_result((conn, address))
|
| 585 |
+
|
| 586 |
+
async def _sendfile_native(self, transp, file, offset, count):
|
| 587 |
+
del self._transports[transp._sock_fd]
|
| 588 |
+
resume_reading = transp.is_reading()
|
| 589 |
+
transp.pause_reading()
|
| 590 |
+
await transp._make_empty_waiter()
|
| 591 |
+
try:
|
| 592 |
+
return await self.sock_sendfile(transp._sock, file, offset, count,
|
| 593 |
+
fallback=False)
|
| 594 |
+
finally:
|
| 595 |
+
transp._reset_empty_waiter()
|
| 596 |
+
if resume_reading:
|
| 597 |
+
transp.resume_reading()
|
| 598 |
+
self._transports[transp._sock_fd] = transp
|
| 599 |
+
|
| 600 |
+
def _process_events(self, event_list):
|
| 601 |
+
for key, mask in event_list:
|
| 602 |
+
fileobj, (reader, writer) = key.fileobj, key.data
|
| 603 |
+
if mask & selectors.EVENT_READ and reader is not None:
|
| 604 |
+
if reader._cancelled:
|
| 605 |
+
self._remove_reader(fileobj)
|
| 606 |
+
else:
|
| 607 |
+
self._add_callback(reader)
|
| 608 |
+
if mask & selectors.EVENT_WRITE and writer is not None:
|
| 609 |
+
if writer._cancelled:
|
| 610 |
+
self._remove_writer(fileobj)
|
| 611 |
+
else:
|
| 612 |
+
self._add_callback(writer)
|
| 613 |
+
|
| 614 |
+
def _stop_serving(self, sock):
|
| 615 |
+
self._remove_reader(sock.fileno())
|
| 616 |
+
sock.close()
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
class _SelectorTransport(transports._FlowControlMixin,
|
| 620 |
+
transports.Transport):
|
| 621 |
+
|
| 622 |
+
max_size = 256 * 1024 # Buffer size passed to recv().
|
| 623 |
+
|
| 624 |
+
_buffer_factory = bytearray # Constructs initial value for self._buffer.
|
| 625 |
+
|
| 626 |
+
# Attribute used in the destructor: it must be set even if the constructor
|
| 627 |
+
# is not called (see _SelectorSslTransport which may start by raising an
|
| 628 |
+
# exception)
|
| 629 |
+
_sock = None
|
| 630 |
+
|
| 631 |
+
def __init__(self, loop, sock, protocol, extra=None, server=None):
|
| 632 |
+
super().__init__(extra, loop)
|
| 633 |
+
self._extra['socket'] = trsock.TransportSocket(sock)
|
| 634 |
+
try:
|
| 635 |
+
self._extra['sockname'] = sock.getsockname()
|
| 636 |
+
except OSError:
|
| 637 |
+
self._extra['sockname'] = None
|
| 638 |
+
if 'peername' not in self._extra:
|
| 639 |
+
try:
|
| 640 |
+
self._extra['peername'] = sock.getpeername()
|
| 641 |
+
except socket.error:
|
| 642 |
+
self._extra['peername'] = None
|
| 643 |
+
self._sock = sock
|
| 644 |
+
self._sock_fd = sock.fileno()
|
| 645 |
+
|
| 646 |
+
self._protocol_connected = False
|
| 647 |
+
self.set_protocol(protocol)
|
| 648 |
+
|
| 649 |
+
self._server = server
|
| 650 |
+
self._buffer = self._buffer_factory()
|
| 651 |
+
self._conn_lost = 0 # Set when call to connection_lost scheduled.
|
| 652 |
+
self._closing = False # Set when close() called.
|
| 653 |
+
if self._server is not None:
|
| 654 |
+
self._server._attach()
|
| 655 |
+
loop._transports[self._sock_fd] = self
|
| 656 |
+
|
| 657 |
+
def __repr__(self):
|
| 658 |
+
info = [self.__class__.__name__]
|
| 659 |
+
if self._sock is None:
|
| 660 |
+
info.append('closed')
|
| 661 |
+
elif self._closing:
|
| 662 |
+
info.append('closing')
|
| 663 |
+
info.append(f'fd={self._sock_fd}')
|
| 664 |
+
# test if the transport was closed
|
| 665 |
+
if self._loop is not None and not self._loop.is_closed():
|
| 666 |
+
polling = _test_selector_event(self._loop._selector,
|
| 667 |
+
self._sock_fd, selectors.EVENT_READ)
|
| 668 |
+
if polling:
|
| 669 |
+
info.append('read=polling')
|
| 670 |
+
else:
|
| 671 |
+
info.append('read=idle')
|
| 672 |
+
|
| 673 |
+
polling = _test_selector_event(self._loop._selector,
|
| 674 |
+
self._sock_fd,
|
| 675 |
+
selectors.EVENT_WRITE)
|
| 676 |
+
if polling:
|
| 677 |
+
state = 'polling'
|
| 678 |
+
else:
|
| 679 |
+
state = 'idle'
|
| 680 |
+
|
| 681 |
+
bufsize = self.get_write_buffer_size()
|
| 682 |
+
info.append(f'write=<{state}, bufsize={bufsize}>')
|
| 683 |
+
return '<{}>'.format(' '.join(info))
|
| 684 |
+
|
| 685 |
+
def abort(self):
|
| 686 |
+
self._force_close(None)
|
| 687 |
+
|
| 688 |
+
def set_protocol(self, protocol):
|
| 689 |
+
self._protocol = protocol
|
| 690 |
+
self._protocol_connected = True
|
| 691 |
+
|
| 692 |
+
def get_protocol(self):
|
| 693 |
+
return self._protocol
|
| 694 |
+
|
| 695 |
+
def is_closing(self):
|
| 696 |
+
return self._closing
|
| 697 |
+
|
| 698 |
+
def close(self):
|
| 699 |
+
if self._closing:
|
| 700 |
+
return
|
| 701 |
+
self._closing = True
|
| 702 |
+
self._loop._remove_reader(self._sock_fd)
|
| 703 |
+
if not self._buffer:
|
| 704 |
+
self._conn_lost += 1
|
| 705 |
+
self._loop._remove_writer(self._sock_fd)
|
| 706 |
+
self._loop.call_soon(self._call_connection_lost, None)
|
| 707 |
+
|
| 708 |
+
def __del__(self, _warn=warnings.warn):
|
| 709 |
+
if self._sock is not None:
|
| 710 |
+
_warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
|
| 711 |
+
self._sock.close()
|
| 712 |
+
|
| 713 |
+
def _fatal_error(self, exc, message='Fatal error on transport'):
|
| 714 |
+
# Should be called from exception handler only.
|
| 715 |
+
if isinstance(exc, OSError):
|
| 716 |
+
if self._loop.get_debug():
|
| 717 |
+
logger.debug("%r: %s", self, message, exc_info=True)
|
| 718 |
+
else:
|
| 719 |
+
self._loop.call_exception_handler({
|
| 720 |
+
'message': message,
|
| 721 |
+
'exception': exc,
|
| 722 |
+
'transport': self,
|
| 723 |
+
'protocol': self._protocol,
|
| 724 |
+
})
|
| 725 |
+
self._force_close(exc)
|
| 726 |
+
|
| 727 |
+
def _force_close(self, exc):
|
| 728 |
+
if self._conn_lost:
|
| 729 |
+
return
|
| 730 |
+
if self._buffer:
|
| 731 |
+
self._buffer.clear()
|
| 732 |
+
self._loop._remove_writer(self._sock_fd)
|
| 733 |
+
if not self._closing:
|
| 734 |
+
self._closing = True
|
| 735 |
+
self._loop._remove_reader(self._sock_fd)
|
| 736 |
+
self._conn_lost += 1
|
| 737 |
+
self._loop.call_soon(self._call_connection_lost, exc)
|
| 738 |
+
|
| 739 |
+
def _call_connection_lost(self, exc):
|
| 740 |
+
try:
|
| 741 |
+
if self._protocol_connected:
|
| 742 |
+
self._protocol.connection_lost(exc)
|
| 743 |
+
finally:
|
| 744 |
+
self._sock.close()
|
| 745 |
+
self._sock = None
|
| 746 |
+
self._protocol = None
|
| 747 |
+
self._loop = None
|
| 748 |
+
server = self._server
|
| 749 |
+
if server is not None:
|
| 750 |
+
server._detach()
|
| 751 |
+
self._server = None
|
| 752 |
+
|
| 753 |
+
def get_write_buffer_size(self):
|
| 754 |
+
return len(self._buffer)
|
| 755 |
+
|
| 756 |
+
def _add_reader(self, fd, callback, *args):
|
| 757 |
+
if self._closing:
|
| 758 |
+
return
|
| 759 |
+
|
| 760 |
+
self._loop._add_reader(fd, callback, *args)
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
class _SelectorSocketTransport(_SelectorTransport):
|
| 764 |
+
|
| 765 |
+
_start_tls_compatible = True
|
| 766 |
+
_sendfile_compatible = constants._SendfileMode.TRY_NATIVE
|
| 767 |
+
|
| 768 |
+
def __init__(self, loop, sock, protocol, waiter=None,
|
| 769 |
+
extra=None, server=None):
|
| 770 |
+
|
| 771 |
+
self._read_ready_cb = None
|
| 772 |
+
super().__init__(loop, sock, protocol, extra, server)
|
| 773 |
+
self._eof = False
|
| 774 |
+
self._paused = False
|
| 775 |
+
self._empty_waiter = None
|
| 776 |
+
|
| 777 |
+
# Disable the Nagle algorithm -- small writes will be
|
| 778 |
+
# sent without waiting for the TCP ACK. This generally
|
| 779 |
+
# decreases the latency (in some cases significantly.)
|
| 780 |
+
base_events._set_nodelay(self._sock)
|
| 781 |
+
|
| 782 |
+
self._loop.call_soon(self._protocol.connection_made, self)
|
| 783 |
+
# only start reading when connection_made() has been called
|
| 784 |
+
self._loop.call_soon(self._add_reader,
|
| 785 |
+
self._sock_fd, self._read_ready)
|
| 786 |
+
if waiter is not None:
|
| 787 |
+
# only wake up the waiter when connection_made() has been called
|
| 788 |
+
self._loop.call_soon(futures._set_result_unless_cancelled,
|
| 789 |
+
waiter, None)
|
| 790 |
+
|
| 791 |
+
def set_protocol(self, protocol):
|
| 792 |
+
if isinstance(protocol, protocols.BufferedProtocol):
|
| 793 |
+
self._read_ready_cb = self._read_ready__get_buffer
|
| 794 |
+
else:
|
| 795 |
+
self._read_ready_cb = self._read_ready__data_received
|
| 796 |
+
|
| 797 |
+
super().set_protocol(protocol)
|
| 798 |
+
|
| 799 |
+
def is_reading(self):
|
| 800 |
+
return not self._paused and not self._closing
|
| 801 |
+
|
| 802 |
+
def pause_reading(self):
|
| 803 |
+
if self._closing or self._paused:
|
| 804 |
+
return
|
| 805 |
+
self._paused = True
|
| 806 |
+
self._loop._remove_reader(self._sock_fd)
|
| 807 |
+
if self._loop.get_debug():
|
| 808 |
+
logger.debug("%r pauses reading", self)
|
| 809 |
+
|
| 810 |
+
def resume_reading(self):
|
| 811 |
+
if self._closing or not self._paused:
|
| 812 |
+
return
|
| 813 |
+
self._paused = False
|
| 814 |
+
self._add_reader(self._sock_fd, self._read_ready)
|
| 815 |
+
if self._loop.get_debug():
|
| 816 |
+
logger.debug("%r resumes reading", self)
|
| 817 |
+
|
| 818 |
+
def _read_ready(self):
|
| 819 |
+
self._read_ready_cb()
|
| 820 |
+
|
| 821 |
+
def _read_ready__get_buffer(self):
|
| 822 |
+
if self._conn_lost:
|
| 823 |
+
return
|
| 824 |
+
|
| 825 |
+
try:
|
| 826 |
+
buf = self._protocol.get_buffer(-1)
|
| 827 |
+
if not len(buf):
|
| 828 |
+
raise RuntimeError('get_buffer() returned an empty buffer')
|
| 829 |
+
except (SystemExit, KeyboardInterrupt):
|
| 830 |
+
raise
|
| 831 |
+
except BaseException as exc:
|
| 832 |
+
self._fatal_error(
|
| 833 |
+
exc, 'Fatal error: protocol.get_buffer() call failed.')
|
| 834 |
+
return
|
| 835 |
+
|
| 836 |
+
try:
|
| 837 |
+
nbytes = self._sock.recv_into(buf)
|
| 838 |
+
except (BlockingIOError, InterruptedError):
|
| 839 |
+
return
|
| 840 |
+
except (SystemExit, KeyboardInterrupt):
|
| 841 |
+
raise
|
| 842 |
+
except BaseException as exc:
|
| 843 |
+
self._fatal_error(exc, 'Fatal read error on socket transport')
|
| 844 |
+
return
|
| 845 |
+
|
| 846 |
+
if not nbytes:
|
| 847 |
+
self._read_ready__on_eof()
|
| 848 |
+
return
|
| 849 |
+
|
| 850 |
+
try:
|
| 851 |
+
self._protocol.buffer_updated(nbytes)
|
| 852 |
+
except (SystemExit, KeyboardInterrupt):
|
| 853 |
+
raise
|
| 854 |
+
except BaseException as exc:
|
| 855 |
+
self._fatal_error(
|
| 856 |
+
exc, 'Fatal error: protocol.buffer_updated() call failed.')
|
| 857 |
+
|
| 858 |
+
def _read_ready__data_received(self):
|
| 859 |
+
if self._conn_lost:
|
| 860 |
+
return
|
| 861 |
+
try:
|
| 862 |
+
data = self._sock.recv(self.max_size)
|
| 863 |
+
except (BlockingIOError, InterruptedError):
|
| 864 |
+
return
|
| 865 |
+
except (SystemExit, KeyboardInterrupt):
|
| 866 |
+
raise
|
| 867 |
+
except BaseException as exc:
|
| 868 |
+
self._fatal_error(exc, 'Fatal read error on socket transport')
|
| 869 |
+
return
|
| 870 |
+
|
| 871 |
+
if not data:
|
| 872 |
+
self._read_ready__on_eof()
|
| 873 |
+
return
|
| 874 |
+
|
| 875 |
+
try:
|
| 876 |
+
self._protocol.data_received(data)
|
| 877 |
+
except (SystemExit, KeyboardInterrupt):
|
| 878 |
+
raise
|
| 879 |
+
except BaseException as exc:
|
| 880 |
+
self._fatal_error(
|
| 881 |
+
exc, 'Fatal error: protocol.data_received() call failed.')
|
| 882 |
+
|
| 883 |
+
def _read_ready__on_eof(self):
|
| 884 |
+
if self._loop.get_debug():
|
| 885 |
+
logger.debug("%r received EOF", self)
|
| 886 |
+
|
| 887 |
+
try:
|
| 888 |
+
keep_open = self._protocol.eof_received()
|
| 889 |
+
except (SystemExit, KeyboardInterrupt):
|
| 890 |
+
raise
|
| 891 |
+
except BaseException as exc:
|
| 892 |
+
self._fatal_error(
|
| 893 |
+
exc, 'Fatal error: protocol.eof_received() call failed.')
|
| 894 |
+
return
|
| 895 |
+
|
| 896 |
+
if keep_open:
|
| 897 |
+
# We're keeping the connection open so the
|
| 898 |
+
# protocol can write more, but we still can't
|
| 899 |
+
# receive more, so remove the reader callback.
|
| 900 |
+
self._loop._remove_reader(self._sock_fd)
|
| 901 |
+
else:
|
| 902 |
+
self.close()
|
| 903 |
+
|
| 904 |
+
def write(self, data):
|
| 905 |
+
if not isinstance(data, (bytes, bytearray, memoryview)):
|
| 906 |
+
raise TypeError(f'data argument must be a bytes-like object, '
|
| 907 |
+
f'not {type(data).__name__!r}')
|
| 908 |
+
if self._eof:
|
| 909 |
+
raise RuntimeError('Cannot call write() after write_eof()')
|
| 910 |
+
if self._empty_waiter is not None:
|
| 911 |
+
raise RuntimeError('unable to write; sendfile is in progress')
|
| 912 |
+
if not data:
|
| 913 |
+
return
|
| 914 |
+
|
| 915 |
+
if self._conn_lost:
|
| 916 |
+
if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
|
| 917 |
+
logger.warning('socket.send() raised exception.')
|
| 918 |
+
self._conn_lost += 1
|
| 919 |
+
return
|
| 920 |
+
|
| 921 |
+
if not self._buffer:
|
| 922 |
+
# Optimization: try to send now.
|
| 923 |
+
try:
|
| 924 |
+
n = self._sock.send(data)
|
| 925 |
+
except (BlockingIOError, InterruptedError):
|
| 926 |
+
pass
|
| 927 |
+
except (SystemExit, KeyboardInterrupt):
|
| 928 |
+
raise
|
| 929 |
+
except BaseException as exc:
|
| 930 |
+
self._fatal_error(exc, 'Fatal write error on socket transport')
|
| 931 |
+
return
|
| 932 |
+
else:
|
| 933 |
+
data = data[n:]
|
| 934 |
+
if not data:
|
| 935 |
+
return
|
| 936 |
+
# Not all was written; register write handler.
|
| 937 |
+
self._loop._add_writer(self._sock_fd, self._write_ready)
|
| 938 |
+
|
| 939 |
+
# Add it to the buffer.
|
| 940 |
+
self._buffer.extend(data)
|
| 941 |
+
self._maybe_pause_protocol()
|
| 942 |
+
|
| 943 |
+
def _write_ready(self):
|
| 944 |
+
assert self._buffer, 'Data should not be empty'
|
| 945 |
+
|
| 946 |
+
if self._conn_lost:
|
| 947 |
+
return
|
| 948 |
+
try:
|
| 949 |
+
n = self._sock.send(self._buffer)
|
| 950 |
+
except (BlockingIOError, InterruptedError):
|
| 951 |
+
pass
|
| 952 |
+
except (SystemExit, KeyboardInterrupt):
|
| 953 |
+
raise
|
| 954 |
+
except BaseException as exc:
|
| 955 |
+
self._loop._remove_writer(self._sock_fd)
|
| 956 |
+
self._buffer.clear()
|
| 957 |
+
self._fatal_error(exc, 'Fatal write error on socket transport')
|
| 958 |
+
if self._empty_waiter is not None:
|
| 959 |
+
self._empty_waiter.set_exception(exc)
|
| 960 |
+
else:
|
| 961 |
+
if n:
|
| 962 |
+
del self._buffer[:n]
|
| 963 |
+
self._maybe_resume_protocol() # May append to buffer.
|
| 964 |
+
if not self._buffer:
|
| 965 |
+
self._loop._remove_writer(self._sock_fd)
|
| 966 |
+
if self._empty_waiter is not None:
|
| 967 |
+
self._empty_waiter.set_result(None)
|
| 968 |
+
if self._closing:
|
| 969 |
+
self._call_connection_lost(None)
|
| 970 |
+
elif self._eof:
|
| 971 |
+
self._sock.shutdown(socket.SHUT_WR)
|
| 972 |
+
|
| 973 |
+
def write_eof(self):
|
| 974 |
+
if self._closing or self._eof:
|
| 975 |
+
return
|
| 976 |
+
self._eof = True
|
| 977 |
+
if not self._buffer:
|
| 978 |
+
self._sock.shutdown(socket.SHUT_WR)
|
| 979 |
+
|
| 980 |
+
def can_write_eof(self):
|
| 981 |
+
return True
|
| 982 |
+
|
| 983 |
+
def _call_connection_lost(self, exc):
|
| 984 |
+
super()._call_connection_lost(exc)
|
| 985 |
+
if self._empty_waiter is not None:
|
| 986 |
+
self._empty_waiter.set_exception(
|
| 987 |
+
ConnectionError("Connection is closed by peer"))
|
| 988 |
+
|
| 989 |
+
def _make_empty_waiter(self):
|
| 990 |
+
if self._empty_waiter is not None:
|
| 991 |
+
raise RuntimeError("Empty waiter is already set")
|
| 992 |
+
self._empty_waiter = self._loop.create_future()
|
| 993 |
+
if not self._buffer:
|
| 994 |
+
self._empty_waiter.set_result(None)
|
| 995 |
+
return self._empty_waiter
|
| 996 |
+
|
| 997 |
+
def _reset_empty_waiter(self):
|
| 998 |
+
self._empty_waiter = None
|
| 999 |
+
|
| 1000 |
+
|
| 1001 |
+
class _SelectorDatagramTransport(_SelectorTransport):
|
| 1002 |
+
|
| 1003 |
+
_buffer_factory = collections.deque
|
| 1004 |
+
|
| 1005 |
+
def __init__(self, loop, sock, protocol, address=None,
|
| 1006 |
+
waiter=None, extra=None):
|
| 1007 |
+
super().__init__(loop, sock, protocol, extra)
|
| 1008 |
+
self._address = address
|
| 1009 |
+
self._loop.call_soon(self._protocol.connection_made, self)
|
| 1010 |
+
# only start reading when connection_made() has been called
|
| 1011 |
+
self._loop.call_soon(self._add_reader,
|
| 1012 |
+
self._sock_fd, self._read_ready)
|
| 1013 |
+
if waiter is not None:
|
| 1014 |
+
# only wake up the waiter when connection_made() has been called
|
| 1015 |
+
self._loop.call_soon(futures._set_result_unless_cancelled,
|
| 1016 |
+
waiter, None)
|
| 1017 |
+
|
| 1018 |
+
def get_write_buffer_size(self):
|
| 1019 |
+
return sum(len(data) for data, _ in self._buffer)
|
| 1020 |
+
|
| 1021 |
+
def _read_ready(self):
|
| 1022 |
+
if self._conn_lost:
|
| 1023 |
+
return
|
| 1024 |
+
try:
|
| 1025 |
+
data, addr = self._sock.recvfrom(self.max_size)
|
| 1026 |
+
except (BlockingIOError, InterruptedError):
|
| 1027 |
+
pass
|
| 1028 |
+
except OSError as exc:
|
| 1029 |
+
self._protocol.error_received(exc)
|
| 1030 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1031 |
+
raise
|
| 1032 |
+
except BaseException as exc:
|
| 1033 |
+
self._fatal_error(exc, 'Fatal read error on datagram transport')
|
| 1034 |
+
else:
|
| 1035 |
+
self._protocol.datagram_received(data, addr)
|
| 1036 |
+
|
| 1037 |
+
def sendto(self, data, addr=None):
|
| 1038 |
+
if not isinstance(data, (bytes, bytearray, memoryview)):
|
| 1039 |
+
raise TypeError(f'data argument must be a bytes-like object, '
|
| 1040 |
+
f'not {type(data).__name__!r}')
|
| 1041 |
+
if not data:
|
| 1042 |
+
return
|
| 1043 |
+
|
| 1044 |
+
if self._address:
|
| 1045 |
+
if addr not in (None, self._address):
|
| 1046 |
+
raise ValueError(
|
| 1047 |
+
f'Invalid address: must be None or {self._address}')
|
| 1048 |
+
addr = self._address
|
| 1049 |
+
|
| 1050 |
+
if self._conn_lost and self._address:
|
| 1051 |
+
if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
|
| 1052 |
+
logger.warning('socket.send() raised exception.')
|
| 1053 |
+
self._conn_lost += 1
|
| 1054 |
+
return
|
| 1055 |
+
|
| 1056 |
+
if not self._buffer:
|
| 1057 |
+
# Attempt to send it right away first.
|
| 1058 |
+
try:
|
| 1059 |
+
if self._extra['peername']:
|
| 1060 |
+
self._sock.send(data)
|
| 1061 |
+
else:
|
| 1062 |
+
self._sock.sendto(data, addr)
|
| 1063 |
+
return
|
| 1064 |
+
except (BlockingIOError, InterruptedError):
|
| 1065 |
+
self._loop._add_writer(self._sock_fd, self._sendto_ready)
|
| 1066 |
+
except OSError as exc:
|
| 1067 |
+
self._protocol.error_received(exc)
|
| 1068 |
+
return
|
| 1069 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1070 |
+
raise
|
| 1071 |
+
except BaseException as exc:
|
| 1072 |
+
self._fatal_error(
|
| 1073 |
+
exc, 'Fatal write error on datagram transport')
|
| 1074 |
+
return
|
| 1075 |
+
|
| 1076 |
+
# Ensure that what we buffer is immutable.
|
| 1077 |
+
self._buffer.append((bytes(data), addr))
|
| 1078 |
+
self._maybe_pause_protocol()
|
| 1079 |
+
|
| 1080 |
+
def _sendto_ready(self):
|
| 1081 |
+
while self._buffer:
|
| 1082 |
+
data, addr = self._buffer.popleft()
|
| 1083 |
+
try:
|
| 1084 |
+
if self._extra['peername']:
|
| 1085 |
+
self._sock.send(data)
|
| 1086 |
+
else:
|
| 1087 |
+
self._sock.sendto(data, addr)
|
| 1088 |
+
except (BlockingIOError, InterruptedError):
|
| 1089 |
+
self._buffer.appendleft((data, addr)) # Try again later.
|
| 1090 |
+
break
|
| 1091 |
+
except OSError as exc:
|
| 1092 |
+
self._protocol.error_received(exc)
|
| 1093 |
+
return
|
| 1094 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1095 |
+
raise
|
| 1096 |
+
except BaseException as exc:
|
| 1097 |
+
self._fatal_error(
|
| 1098 |
+
exc, 'Fatal write error on datagram transport')
|
| 1099 |
+
return
|
| 1100 |
+
|
| 1101 |
+
self._maybe_resume_protocol() # May append to buffer.
|
| 1102 |
+
if not self._buffer:
|
| 1103 |
+
self._loop._remove_writer(self._sock_fd)
|
| 1104 |
+
if self._closing:
|
| 1105 |
+
self._call_connection_lost(None)
|
janus/lib/python3.10/asyncio/subprocess.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__all__ = 'create_subprocess_exec', 'create_subprocess_shell'
|
| 2 |
+
|
| 3 |
+
import subprocess
|
| 4 |
+
|
| 5 |
+
from . import events
|
| 6 |
+
from . import protocols
|
| 7 |
+
from . import streams
|
| 8 |
+
from . import tasks
|
| 9 |
+
from .log import logger
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
PIPE = subprocess.PIPE
|
| 13 |
+
STDOUT = subprocess.STDOUT
|
| 14 |
+
DEVNULL = subprocess.DEVNULL
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class SubprocessStreamProtocol(streams.FlowControlMixin,
|
| 18 |
+
protocols.SubprocessProtocol):
|
| 19 |
+
"""Like StreamReaderProtocol, but for a subprocess."""
|
| 20 |
+
|
| 21 |
+
def __init__(self, limit, loop):
|
| 22 |
+
super().__init__(loop=loop)
|
| 23 |
+
self._limit = limit
|
| 24 |
+
self.stdin = self.stdout = self.stderr = None
|
| 25 |
+
self._transport = None
|
| 26 |
+
self._process_exited = False
|
| 27 |
+
self._pipe_fds = []
|
| 28 |
+
self._stdin_closed = self._loop.create_future()
|
| 29 |
+
|
| 30 |
+
def __repr__(self):
|
| 31 |
+
info = [self.__class__.__name__]
|
| 32 |
+
if self.stdin is not None:
|
| 33 |
+
info.append(f'stdin={self.stdin!r}')
|
| 34 |
+
if self.stdout is not None:
|
| 35 |
+
info.append(f'stdout={self.stdout!r}')
|
| 36 |
+
if self.stderr is not None:
|
| 37 |
+
info.append(f'stderr={self.stderr!r}')
|
| 38 |
+
return '<{}>'.format(' '.join(info))
|
| 39 |
+
|
| 40 |
+
def connection_made(self, transport):
|
| 41 |
+
self._transport = transport
|
| 42 |
+
|
| 43 |
+
stdout_transport = transport.get_pipe_transport(1)
|
| 44 |
+
if stdout_transport is not None:
|
| 45 |
+
self.stdout = streams.StreamReader(limit=self._limit,
|
| 46 |
+
loop=self._loop)
|
| 47 |
+
self.stdout.set_transport(stdout_transport)
|
| 48 |
+
self._pipe_fds.append(1)
|
| 49 |
+
|
| 50 |
+
stderr_transport = transport.get_pipe_transport(2)
|
| 51 |
+
if stderr_transport is not None:
|
| 52 |
+
self.stderr = streams.StreamReader(limit=self._limit,
|
| 53 |
+
loop=self._loop)
|
| 54 |
+
self.stderr.set_transport(stderr_transport)
|
| 55 |
+
self._pipe_fds.append(2)
|
| 56 |
+
|
| 57 |
+
stdin_transport = transport.get_pipe_transport(0)
|
| 58 |
+
if stdin_transport is not None:
|
| 59 |
+
self.stdin = streams.StreamWriter(stdin_transport,
|
| 60 |
+
protocol=self,
|
| 61 |
+
reader=None,
|
| 62 |
+
loop=self._loop)
|
| 63 |
+
|
| 64 |
+
def pipe_data_received(self, fd, data):
|
| 65 |
+
if fd == 1:
|
| 66 |
+
reader = self.stdout
|
| 67 |
+
elif fd == 2:
|
| 68 |
+
reader = self.stderr
|
| 69 |
+
else:
|
| 70 |
+
reader = None
|
| 71 |
+
if reader is not None:
|
| 72 |
+
reader.feed_data(data)
|
| 73 |
+
|
| 74 |
+
def pipe_connection_lost(self, fd, exc):
|
| 75 |
+
if fd == 0:
|
| 76 |
+
pipe = self.stdin
|
| 77 |
+
if pipe is not None:
|
| 78 |
+
pipe.close()
|
| 79 |
+
self.connection_lost(exc)
|
| 80 |
+
if exc is None:
|
| 81 |
+
self._stdin_closed.set_result(None)
|
| 82 |
+
else:
|
| 83 |
+
self._stdin_closed.set_exception(exc)
|
| 84 |
+
return
|
| 85 |
+
if fd == 1:
|
| 86 |
+
reader = self.stdout
|
| 87 |
+
elif fd == 2:
|
| 88 |
+
reader = self.stderr
|
| 89 |
+
else:
|
| 90 |
+
reader = None
|
| 91 |
+
if reader is not None:
|
| 92 |
+
if exc is None:
|
| 93 |
+
reader.feed_eof()
|
| 94 |
+
else:
|
| 95 |
+
reader.set_exception(exc)
|
| 96 |
+
|
| 97 |
+
if fd in self._pipe_fds:
|
| 98 |
+
self._pipe_fds.remove(fd)
|
| 99 |
+
self._maybe_close_transport()
|
| 100 |
+
|
| 101 |
+
def process_exited(self):
|
| 102 |
+
self._process_exited = True
|
| 103 |
+
self._maybe_close_transport()
|
| 104 |
+
|
| 105 |
+
def _maybe_close_transport(self):
|
| 106 |
+
if len(self._pipe_fds) == 0 and self._process_exited:
|
| 107 |
+
self._transport.close()
|
| 108 |
+
self._transport = None
|
| 109 |
+
|
| 110 |
+
def _get_close_waiter(self, stream):
|
| 111 |
+
if stream is self.stdin:
|
| 112 |
+
return self._stdin_closed
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class Process:
|
| 116 |
+
def __init__(self, transport, protocol, loop):
|
| 117 |
+
self._transport = transport
|
| 118 |
+
self._protocol = protocol
|
| 119 |
+
self._loop = loop
|
| 120 |
+
self.stdin = protocol.stdin
|
| 121 |
+
self.stdout = protocol.stdout
|
| 122 |
+
self.stderr = protocol.stderr
|
| 123 |
+
self.pid = transport.get_pid()
|
| 124 |
+
|
| 125 |
+
def __repr__(self):
|
| 126 |
+
return f'<{self.__class__.__name__} {self.pid}>'
|
| 127 |
+
|
| 128 |
+
@property
|
| 129 |
+
def returncode(self):
|
| 130 |
+
return self._transport.get_returncode()
|
| 131 |
+
|
| 132 |
+
async def wait(self):
|
| 133 |
+
"""Wait until the process exit and return the process return code."""
|
| 134 |
+
return await self._transport._wait()
|
| 135 |
+
|
| 136 |
+
def send_signal(self, signal):
|
| 137 |
+
self._transport.send_signal(signal)
|
| 138 |
+
|
| 139 |
+
def terminate(self):
|
| 140 |
+
self._transport.terminate()
|
| 141 |
+
|
| 142 |
+
def kill(self):
|
| 143 |
+
self._transport.kill()
|
| 144 |
+
|
| 145 |
+
async def _feed_stdin(self, input):
|
| 146 |
+
debug = self._loop.get_debug()
|
| 147 |
+
self.stdin.write(input)
|
| 148 |
+
if debug:
|
| 149 |
+
logger.debug(
|
| 150 |
+
'%r communicate: feed stdin (%s bytes)', self, len(input))
|
| 151 |
+
try:
|
| 152 |
+
await self.stdin.drain()
|
| 153 |
+
except (BrokenPipeError, ConnectionResetError) as exc:
|
| 154 |
+
# communicate() ignores BrokenPipeError and ConnectionResetError
|
| 155 |
+
if debug:
|
| 156 |
+
logger.debug('%r communicate: stdin got %r', self, exc)
|
| 157 |
+
|
| 158 |
+
if debug:
|
| 159 |
+
logger.debug('%r communicate: close stdin', self)
|
| 160 |
+
self.stdin.close()
|
| 161 |
+
|
| 162 |
+
async def _noop(self):
|
| 163 |
+
return None
|
| 164 |
+
|
| 165 |
+
async def _read_stream(self, fd):
|
| 166 |
+
transport = self._transport.get_pipe_transport(fd)
|
| 167 |
+
if fd == 2:
|
| 168 |
+
stream = self.stderr
|
| 169 |
+
else:
|
| 170 |
+
assert fd == 1
|
| 171 |
+
stream = self.stdout
|
| 172 |
+
if self._loop.get_debug():
|
| 173 |
+
name = 'stdout' if fd == 1 else 'stderr'
|
| 174 |
+
logger.debug('%r communicate: read %s', self, name)
|
| 175 |
+
output = await stream.read()
|
| 176 |
+
if self._loop.get_debug():
|
| 177 |
+
name = 'stdout' if fd == 1 else 'stderr'
|
| 178 |
+
logger.debug('%r communicate: close %s', self, name)
|
| 179 |
+
transport.close()
|
| 180 |
+
return output
|
| 181 |
+
|
| 182 |
+
async def communicate(self, input=None):
|
| 183 |
+
if input is not None:
|
| 184 |
+
stdin = self._feed_stdin(input)
|
| 185 |
+
else:
|
| 186 |
+
stdin = self._noop()
|
| 187 |
+
if self.stdout is not None:
|
| 188 |
+
stdout = self._read_stream(1)
|
| 189 |
+
else:
|
| 190 |
+
stdout = self._noop()
|
| 191 |
+
if self.stderr is not None:
|
| 192 |
+
stderr = self._read_stream(2)
|
| 193 |
+
else:
|
| 194 |
+
stderr = self._noop()
|
| 195 |
+
stdin, stdout, stderr = await tasks.gather(stdin, stdout, stderr)
|
| 196 |
+
await self.wait()
|
| 197 |
+
return (stdout, stderr)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
async def create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None,
|
| 201 |
+
limit=streams._DEFAULT_LIMIT, **kwds):
|
| 202 |
+
loop = events.get_running_loop()
|
| 203 |
+
protocol_factory = lambda: SubprocessStreamProtocol(limit=limit,
|
| 204 |
+
loop=loop)
|
| 205 |
+
transport, protocol = await loop.subprocess_shell(
|
| 206 |
+
protocol_factory,
|
| 207 |
+
cmd, stdin=stdin, stdout=stdout,
|
| 208 |
+
stderr=stderr, **kwds)
|
| 209 |
+
return Process(transport, protocol, loop)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
async def create_subprocess_exec(program, *args, stdin=None, stdout=None,
|
| 213 |
+
stderr=None, limit=streams._DEFAULT_LIMIT,
|
| 214 |
+
**kwds):
|
| 215 |
+
loop = events.get_running_loop()
|
| 216 |
+
protocol_factory = lambda: SubprocessStreamProtocol(limit=limit,
|
| 217 |
+
loop=loop)
|
| 218 |
+
transport, protocol = await loop.subprocess_exec(
|
| 219 |
+
protocol_factory,
|
| 220 |
+
program, *args,
|
| 221 |
+
stdin=stdin, stdout=stdout,
|
| 222 |
+
stderr=stderr, **kwds)
|
| 223 |
+
return Process(transport, protocol, loop)
|
janus/lib/python3.10/asyncio/tasks.py
ADDED
|
@@ -0,0 +1,946 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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future', 'run_coroutine_threadsafe',
|
| 8 |
+
'current_task', 'all_tasks',
|
| 9 |
+
'_register_task', '_unregister_task', '_enter_task', '_leave_task',
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
import concurrent.futures
|
| 13 |
+
import contextvars
|
| 14 |
+
import functools
|
| 15 |
+
import inspect
|
| 16 |
+
import itertools
|
| 17 |
+
import types
|
| 18 |
+
import warnings
|
| 19 |
+
import weakref
|
| 20 |
+
from types import GenericAlias
|
| 21 |
+
|
| 22 |
+
from . import base_tasks
|
| 23 |
+
from . import coroutines
|
| 24 |
+
from . import events
|
| 25 |
+
from . import exceptions
|
| 26 |
+
from . import futures
|
| 27 |
+
from .coroutines import _is_coroutine
|
| 28 |
+
|
| 29 |
+
# Helper to generate new task names
|
| 30 |
+
# This uses itertools.count() instead of a "+= 1" operation because the latter
|
| 31 |
+
# is not thread safe. See bpo-11866 for a longer explanation.
|
| 32 |
+
_task_name_counter = itertools.count(1).__next__
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def current_task(loop=None):
|
| 36 |
+
"""Return a currently executed task."""
|
| 37 |
+
if loop is None:
|
| 38 |
+
loop = events.get_running_loop()
|
| 39 |
+
return _current_tasks.get(loop)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def all_tasks(loop=None):
|
| 43 |
+
"""Return a set of all tasks for the loop."""
|
| 44 |
+
if loop is None:
|
| 45 |
+
loop = events.get_running_loop()
|
| 46 |
+
# Looping over a WeakSet (_all_tasks) isn't safe as it can be updated from another
|
| 47 |
+
# thread while we do so. Therefore we cast it to list prior to filtering. The list
|
| 48 |
+
# cast itself requires iteration, so we repeat it several times ignoring
|
| 49 |
+
# RuntimeErrors (which are not very likely to occur). See issues 34970 and 36607 for
|
| 50 |
+
# details.
|
| 51 |
+
i = 0
|
| 52 |
+
while True:
|
| 53 |
+
try:
|
| 54 |
+
tasks = list(_all_tasks)
|
| 55 |
+
except RuntimeError:
|
| 56 |
+
i += 1
|
| 57 |
+
if i >= 1000:
|
| 58 |
+
raise
|
| 59 |
+
else:
|
| 60 |
+
break
|
| 61 |
+
return {t for t in tasks
|
| 62 |
+
if futures._get_loop(t) is loop and not t.done()}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _set_task_name(task, name):
|
| 66 |
+
if name is not None:
|
| 67 |
+
try:
|
| 68 |
+
set_name = task.set_name
|
| 69 |
+
except AttributeError:
|
| 70 |
+
pass
|
| 71 |
+
else:
|
| 72 |
+
set_name(name)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class Task(futures._PyFuture): # Inherit Python Task implementation
|
| 76 |
+
# from a Python Future implementation.
|
| 77 |
+
|
| 78 |
+
"""A coroutine wrapped in a Future."""
|
| 79 |
+
|
| 80 |
+
# An important invariant maintained while a Task not done:
|
| 81 |
+
#
|
| 82 |
+
# - Either _fut_waiter is None, and _step() is scheduled;
|
| 83 |
+
# - or _fut_waiter is some Future, and _step() is *not* scheduled.
|
| 84 |
+
#
|
| 85 |
+
# The only transition from the latter to the former is through
|
| 86 |
+
# _wakeup(). When _fut_waiter is not None, one of its callbacks
|
| 87 |
+
# must be _wakeup().
|
| 88 |
+
|
| 89 |
+
# If False, don't log a message if the task is destroyed whereas its
|
| 90 |
+
# status is still pending
|
| 91 |
+
_log_destroy_pending = True
|
| 92 |
+
|
| 93 |
+
def __init__(self, coro, *, loop=None, name=None):
|
| 94 |
+
super().__init__(loop=loop)
|
| 95 |
+
if self._source_traceback:
|
| 96 |
+
del self._source_traceback[-1]
|
| 97 |
+
if not coroutines.iscoroutine(coro):
|
| 98 |
+
# raise after Future.__init__(), attrs are required for __del__
|
| 99 |
+
# prevent logging for pending task in __del__
|
| 100 |
+
self._log_destroy_pending = False
|
| 101 |
+
raise TypeError(f"a coroutine was expected, got {coro!r}")
|
| 102 |
+
|
| 103 |
+
if name is None:
|
| 104 |
+
self._name = f'Task-{_task_name_counter()}'
|
| 105 |
+
else:
|
| 106 |
+
self._name = str(name)
|
| 107 |
+
|
| 108 |
+
self._must_cancel = False
|
| 109 |
+
self._fut_waiter = None
|
| 110 |
+
self._coro = coro
|
| 111 |
+
self._context = contextvars.copy_context()
|
| 112 |
+
|
| 113 |
+
self._loop.call_soon(self.__step, context=self._context)
|
| 114 |
+
_register_task(self)
|
| 115 |
+
|
| 116 |
+
def __del__(self):
|
| 117 |
+
if self._state == futures._PENDING and self._log_destroy_pending:
|
| 118 |
+
context = {
|
| 119 |
+
'task': self,
|
| 120 |
+
'message': 'Task was destroyed but it is pending!',
|
| 121 |
+
}
|
| 122 |
+
if self._source_traceback:
|
| 123 |
+
context['source_traceback'] = self._source_traceback
|
| 124 |
+
self._loop.call_exception_handler(context)
|
| 125 |
+
super().__del__()
|
| 126 |
+
|
| 127 |
+
__class_getitem__ = classmethod(GenericAlias)
|
| 128 |
+
|
| 129 |
+
def _repr_info(self):
|
| 130 |
+
return base_tasks._task_repr_info(self)
|
| 131 |
+
|
| 132 |
+
def get_coro(self):
|
| 133 |
+
return self._coro
|
| 134 |
+
|
| 135 |
+
def get_name(self):
|
| 136 |
+
return self._name
|
| 137 |
+
|
| 138 |
+
def set_name(self, value):
|
| 139 |
+
self._name = str(value)
|
| 140 |
+
|
| 141 |
+
def set_result(self, result):
|
| 142 |
+
raise RuntimeError('Task does not support set_result operation')
|
| 143 |
+
|
| 144 |
+
def set_exception(self, exception):
|
| 145 |
+
raise RuntimeError('Task does not support set_exception operation')
|
| 146 |
+
|
| 147 |
+
def get_stack(self, *, limit=None):
|
| 148 |
+
"""Return the list of stack frames for this task's coroutine.
|
| 149 |
+
|
| 150 |
+
If the coroutine is not done, this returns the stack where it is
|
| 151 |
+
suspended. If the coroutine has completed successfully or was
|
| 152 |
+
cancelled, this returns an empty list. If the coroutine was
|
| 153 |
+
terminated by an exception, this returns the list of traceback
|
| 154 |
+
frames.
|
| 155 |
+
|
| 156 |
+
The frames are always ordered from oldest to newest.
|
| 157 |
+
|
| 158 |
+
The optional limit gives the maximum number of frames to
|
| 159 |
+
return; by default all available frames are returned. Its
|
| 160 |
+
meaning differs depending on whether a stack or a traceback is
|
| 161 |
+
returned: the newest frames of a stack are returned, but the
|
| 162 |
+
oldest frames of a traceback are returned. (This matches the
|
| 163 |
+
behavior of the traceback module.)
|
| 164 |
+
|
| 165 |
+
For reasons beyond our control, only one stack frame is
|
| 166 |
+
returned for a suspended coroutine.
|
| 167 |
+
"""
|
| 168 |
+
return base_tasks._task_get_stack(self, limit)
|
| 169 |
+
|
| 170 |
+
def print_stack(self, *, limit=None, file=None):
|
| 171 |
+
"""Print the stack or traceback for this task's coroutine.
|
| 172 |
+
|
| 173 |
+
This produces output similar to that of the traceback module,
|
| 174 |
+
for the frames retrieved by get_stack(). The limit argument
|
| 175 |
+
is passed to get_stack(). The file argument is an I/O stream
|
| 176 |
+
to which the output is written; by default output is written
|
| 177 |
+
to sys.stderr.
|
| 178 |
+
"""
|
| 179 |
+
return base_tasks._task_print_stack(self, limit, file)
|
| 180 |
+
|
| 181 |
+
def cancel(self, msg=None):
|
| 182 |
+
"""Request that this task cancel itself.
|
| 183 |
+
|
| 184 |
+
This arranges for a CancelledError to be thrown into the
|
| 185 |
+
wrapped coroutine on the next cycle through the event loop.
|
| 186 |
+
The coroutine then has a chance to clean up or even deny
|
| 187 |
+
the request using try/except/finally.
|
| 188 |
+
|
| 189 |
+
Unlike Future.cancel, this does not guarantee that the
|
| 190 |
+
task will be cancelled: the exception might be caught and
|
| 191 |
+
acted upon, delaying cancellation of the task or preventing
|
| 192 |
+
cancellation completely. The task may also return a value or
|
| 193 |
+
raise a different exception.
|
| 194 |
+
|
| 195 |
+
Immediately after this method is called, Task.cancelled() will
|
| 196 |
+
not return True (unless the task was already cancelled). A
|
| 197 |
+
task will be marked as cancelled when the wrapped coroutine
|
| 198 |
+
terminates with a CancelledError exception (even if cancel()
|
| 199 |
+
was not called).
|
| 200 |
+
"""
|
| 201 |
+
self._log_traceback = False
|
| 202 |
+
if self.done():
|
| 203 |
+
return False
|
| 204 |
+
if self._fut_waiter is not None:
|
| 205 |
+
if self._fut_waiter.cancel(msg=msg):
|
| 206 |
+
# Leave self._fut_waiter; it may be a Task that
|
| 207 |
+
# catches and ignores the cancellation so we may have
|
| 208 |
+
# to cancel it again later.
|
| 209 |
+
return True
|
| 210 |
+
# It must be the case that self.__step is already scheduled.
|
| 211 |
+
self._must_cancel = True
|
| 212 |
+
self._cancel_message = msg
|
| 213 |
+
return True
|
| 214 |
+
|
| 215 |
+
def __step(self, exc=None):
|
| 216 |
+
if self.done():
|
| 217 |
+
raise exceptions.InvalidStateError(
|
| 218 |
+
f'_step(): already done: {self!r}, {exc!r}')
|
| 219 |
+
if self._must_cancel:
|
| 220 |
+
if not isinstance(exc, exceptions.CancelledError):
|
| 221 |
+
exc = self._make_cancelled_error()
|
| 222 |
+
self._must_cancel = False
|
| 223 |
+
coro = self._coro
|
| 224 |
+
self._fut_waiter = None
|
| 225 |
+
|
| 226 |
+
_enter_task(self._loop, self)
|
| 227 |
+
# Call either coro.throw(exc) or coro.send(None).
|
| 228 |
+
try:
|
| 229 |
+
if exc is None:
|
| 230 |
+
# We use the `send` method directly, because coroutines
|
| 231 |
+
# don't have `__iter__` and `__next__` methods.
|
| 232 |
+
result = coro.send(None)
|
| 233 |
+
else:
|
| 234 |
+
result = coro.throw(exc)
|
| 235 |
+
except StopIteration as exc:
|
| 236 |
+
if self._must_cancel:
|
| 237 |
+
# Task is cancelled right before coro stops.
|
| 238 |
+
self._must_cancel = False
|
| 239 |
+
super().cancel(msg=self._cancel_message)
|
| 240 |
+
else:
|
| 241 |
+
super().set_result(exc.value)
|
| 242 |
+
except exceptions.CancelledError as exc:
|
| 243 |
+
# Save the original exception so we can chain it later.
|
| 244 |
+
self._cancelled_exc = exc
|
| 245 |
+
super().cancel() # I.e., Future.cancel(self).
|
| 246 |
+
except (KeyboardInterrupt, SystemExit) as exc:
|
| 247 |
+
super().set_exception(exc)
|
| 248 |
+
raise
|
| 249 |
+
except BaseException as exc:
|
| 250 |
+
super().set_exception(exc)
|
| 251 |
+
else:
|
| 252 |
+
blocking = getattr(result, '_asyncio_future_blocking', None)
|
| 253 |
+
if blocking is not None:
|
| 254 |
+
# Yielded Future must come from Future.__iter__().
|
| 255 |
+
if futures._get_loop(result) is not self._loop:
|
| 256 |
+
new_exc = RuntimeError(
|
| 257 |
+
f'Task {self!r} got Future '
|
| 258 |
+
f'{result!r} attached to a different loop')
|
| 259 |
+
self._loop.call_soon(
|
| 260 |
+
self.__step, new_exc, context=self._context)
|
| 261 |
+
elif blocking:
|
| 262 |
+
if result is self:
|
| 263 |
+
new_exc = RuntimeError(
|
| 264 |
+
f'Task cannot await on itself: {self!r}')
|
| 265 |
+
self._loop.call_soon(
|
| 266 |
+
self.__step, new_exc, context=self._context)
|
| 267 |
+
else:
|
| 268 |
+
result._asyncio_future_blocking = False
|
| 269 |
+
result.add_done_callback(
|
| 270 |
+
self.__wakeup, context=self._context)
|
| 271 |
+
self._fut_waiter = result
|
| 272 |
+
if self._must_cancel:
|
| 273 |
+
if self._fut_waiter.cancel(
|
| 274 |
+
msg=self._cancel_message):
|
| 275 |
+
self._must_cancel = False
|
| 276 |
+
else:
|
| 277 |
+
new_exc = RuntimeError(
|
| 278 |
+
f'yield was used instead of yield from '
|
| 279 |
+
f'in task {self!r} with {result!r}')
|
| 280 |
+
self._loop.call_soon(
|
| 281 |
+
self.__step, new_exc, context=self._context)
|
| 282 |
+
|
| 283 |
+
elif result is None:
|
| 284 |
+
# Bare yield relinquishes control for one event loop iteration.
|
| 285 |
+
self._loop.call_soon(self.__step, context=self._context)
|
| 286 |
+
elif inspect.isgenerator(result):
|
| 287 |
+
# Yielding a generator is just wrong.
|
| 288 |
+
new_exc = RuntimeError(
|
| 289 |
+
f'yield was used instead of yield from for '
|
| 290 |
+
f'generator in task {self!r} with {result!r}')
|
| 291 |
+
self._loop.call_soon(
|
| 292 |
+
self.__step, new_exc, context=self._context)
|
| 293 |
+
else:
|
| 294 |
+
# Yielding something else is an error.
|
| 295 |
+
new_exc = RuntimeError(f'Task got bad yield: {result!r}')
|
| 296 |
+
self._loop.call_soon(
|
| 297 |
+
self.__step, new_exc, context=self._context)
|
| 298 |
+
finally:
|
| 299 |
+
_leave_task(self._loop, self)
|
| 300 |
+
self = None # Needed to break cycles when an exception occurs.
|
| 301 |
+
|
| 302 |
+
def __wakeup(self, future):
|
| 303 |
+
try:
|
| 304 |
+
future.result()
|
| 305 |
+
except BaseException as exc:
|
| 306 |
+
# This may also be a cancellation.
|
| 307 |
+
self.__step(exc)
|
| 308 |
+
else:
|
| 309 |
+
# Don't pass the value of `future.result()` explicitly,
|
| 310 |
+
# as `Future.__iter__` and `Future.__await__` don't need it.
|
| 311 |
+
# If we call `_step(value, None)` instead of `_step()`,
|
| 312 |
+
# Python eval loop would use `.send(value)` method call,
|
| 313 |
+
# instead of `__next__()`, which is slower for futures
|
| 314 |
+
# that return non-generator iterators from their `__iter__`.
|
| 315 |
+
self.__step()
|
| 316 |
+
self = None # Needed to break cycles when an exception occurs.
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
_PyTask = Task
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
try:
|
| 323 |
+
import _asyncio
|
| 324 |
+
except ImportError:
|
| 325 |
+
pass
|
| 326 |
+
else:
|
| 327 |
+
# _CTask is needed for tests.
|
| 328 |
+
Task = _CTask = _asyncio.Task
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def create_task(coro, *, name=None):
|
| 332 |
+
"""Schedule the execution of a coroutine object in a spawn task.
|
| 333 |
+
|
| 334 |
+
Return a Task object.
|
| 335 |
+
"""
|
| 336 |
+
loop = events.get_running_loop()
|
| 337 |
+
task = loop.create_task(coro)
|
| 338 |
+
_set_task_name(task, name)
|
| 339 |
+
return task
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
# wait() and as_completed() similar to those in PEP 3148.
|
| 343 |
+
|
| 344 |
+
FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED
|
| 345 |
+
FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION
|
| 346 |
+
ALL_COMPLETED = concurrent.futures.ALL_COMPLETED
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
async def wait(fs, *, timeout=None, return_when=ALL_COMPLETED):
|
| 350 |
+
"""Wait for the Futures and coroutines given by fs to complete.
|
| 351 |
+
|
| 352 |
+
The fs iterable must not be empty.
|
| 353 |
+
|
| 354 |
+
Coroutines will be wrapped in Tasks.
|
| 355 |
+
|
| 356 |
+
Returns two sets of Future: (done, pending).
|
| 357 |
+
|
| 358 |
+
Usage:
|
| 359 |
+
|
| 360 |
+
done, pending = await asyncio.wait(fs)
|
| 361 |
+
|
| 362 |
+
Note: This does not raise TimeoutError! Futures that aren't done
|
| 363 |
+
when the timeout occurs are returned in the second set.
|
| 364 |
+
"""
|
| 365 |
+
if futures.isfuture(fs) or coroutines.iscoroutine(fs):
|
| 366 |
+
raise TypeError(f"expect a list of futures, not {type(fs).__name__}")
|
| 367 |
+
if not fs:
|
| 368 |
+
raise ValueError('Set of coroutines/Futures is empty.')
|
| 369 |
+
if return_when not in (FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED):
|
| 370 |
+
raise ValueError(f'Invalid return_when value: {return_when}')
|
| 371 |
+
|
| 372 |
+
loop = events.get_running_loop()
|
| 373 |
+
|
| 374 |
+
fs = set(fs)
|
| 375 |
+
|
| 376 |
+
if any(coroutines.iscoroutine(f) for f in fs):
|
| 377 |
+
warnings.warn("The explicit passing of coroutine objects to "
|
| 378 |
+
"asyncio.wait() is deprecated since Python 3.8, and "
|
| 379 |
+
"scheduled for removal in Python 3.11.",
|
| 380 |
+
DeprecationWarning, stacklevel=2)
|
| 381 |
+
|
| 382 |
+
fs = {ensure_future(f, loop=loop) for f in fs}
|
| 383 |
+
|
| 384 |
+
return await _wait(fs, timeout, return_when, loop)
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def _release_waiter(waiter, *args):
|
| 388 |
+
if not waiter.done():
|
| 389 |
+
waiter.set_result(None)
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
async def wait_for(fut, timeout):
|
| 393 |
+
"""Wait for the single Future or coroutine to complete, with timeout.
|
| 394 |
+
|
| 395 |
+
Coroutine will be wrapped in Task.
|
| 396 |
+
|
| 397 |
+
Returns result of the Future or coroutine. When a timeout occurs,
|
| 398 |
+
it cancels the task and raises TimeoutError. To avoid the task
|
| 399 |
+
cancellation, wrap it in shield().
|
| 400 |
+
|
| 401 |
+
If the wait is cancelled, the task is also cancelled.
|
| 402 |
+
|
| 403 |
+
This function is a coroutine.
|
| 404 |
+
"""
|
| 405 |
+
loop = events.get_running_loop()
|
| 406 |
+
|
| 407 |
+
if timeout is None:
|
| 408 |
+
return await fut
|
| 409 |
+
|
| 410 |
+
if timeout <= 0:
|
| 411 |
+
fut = ensure_future(fut, loop=loop)
|
| 412 |
+
|
| 413 |
+
if fut.done():
|
| 414 |
+
return fut.result()
|
| 415 |
+
|
| 416 |
+
await _cancel_and_wait(fut, loop=loop)
|
| 417 |
+
try:
|
| 418 |
+
return fut.result()
|
| 419 |
+
except exceptions.CancelledError as exc:
|
| 420 |
+
raise exceptions.TimeoutError() from exc
|
| 421 |
+
|
| 422 |
+
waiter = loop.create_future()
|
| 423 |
+
timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
|
| 424 |
+
cb = functools.partial(_release_waiter, waiter)
|
| 425 |
+
|
| 426 |
+
fut = ensure_future(fut, loop=loop)
|
| 427 |
+
fut.add_done_callback(cb)
|
| 428 |
+
|
| 429 |
+
try:
|
| 430 |
+
# wait until the future completes or the timeout
|
| 431 |
+
try:
|
| 432 |
+
await waiter
|
| 433 |
+
except exceptions.CancelledError:
|
| 434 |
+
if fut.done():
|
| 435 |
+
return fut.result()
|
| 436 |
+
else:
|
| 437 |
+
fut.remove_done_callback(cb)
|
| 438 |
+
# We must ensure that the task is not running
|
| 439 |
+
# after wait_for() returns.
|
| 440 |
+
# See https://bugs.python.org/issue32751
|
| 441 |
+
await _cancel_and_wait(fut, loop=loop)
|
| 442 |
+
raise
|
| 443 |
+
|
| 444 |
+
if fut.done():
|
| 445 |
+
return fut.result()
|
| 446 |
+
else:
|
| 447 |
+
fut.remove_done_callback(cb)
|
| 448 |
+
# We must ensure that the task is not running
|
| 449 |
+
# after wait_for() returns.
|
| 450 |
+
# See https://bugs.python.org/issue32751
|
| 451 |
+
await _cancel_and_wait(fut, loop=loop)
|
| 452 |
+
# In case task cancellation failed with some
|
| 453 |
+
# exception, we should re-raise it
|
| 454 |
+
# See https://bugs.python.org/issue40607
|
| 455 |
+
try:
|
| 456 |
+
return fut.result()
|
| 457 |
+
except exceptions.CancelledError as exc:
|
| 458 |
+
raise exceptions.TimeoutError() from exc
|
| 459 |
+
finally:
|
| 460 |
+
timeout_handle.cancel()
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
async def _wait(fs, timeout, return_when, loop):
|
| 464 |
+
"""Internal helper for wait().
|
| 465 |
+
|
| 466 |
+
The fs argument must be a collection of Futures.
|
| 467 |
+
"""
|
| 468 |
+
assert fs, 'Set of Futures is empty.'
|
| 469 |
+
waiter = loop.create_future()
|
| 470 |
+
timeout_handle = None
|
| 471 |
+
if timeout is not None:
|
| 472 |
+
timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
|
| 473 |
+
counter = len(fs)
|
| 474 |
+
|
| 475 |
+
def _on_completion(f):
|
| 476 |
+
nonlocal counter
|
| 477 |
+
counter -= 1
|
| 478 |
+
if (counter <= 0 or
|
| 479 |
+
return_when == FIRST_COMPLETED or
|
| 480 |
+
return_when == FIRST_EXCEPTION and (not f.cancelled() and
|
| 481 |
+
f.exception() is not None)):
|
| 482 |
+
if timeout_handle is not None:
|
| 483 |
+
timeout_handle.cancel()
|
| 484 |
+
if not waiter.done():
|
| 485 |
+
waiter.set_result(None)
|
| 486 |
+
|
| 487 |
+
for f in fs:
|
| 488 |
+
f.add_done_callback(_on_completion)
|
| 489 |
+
|
| 490 |
+
try:
|
| 491 |
+
await waiter
|
| 492 |
+
finally:
|
| 493 |
+
if timeout_handle is not None:
|
| 494 |
+
timeout_handle.cancel()
|
| 495 |
+
for f in fs:
|
| 496 |
+
f.remove_done_callback(_on_completion)
|
| 497 |
+
|
| 498 |
+
done, pending = set(), set()
|
| 499 |
+
for f in fs:
|
| 500 |
+
if f.done():
|
| 501 |
+
done.add(f)
|
| 502 |
+
else:
|
| 503 |
+
pending.add(f)
|
| 504 |
+
return done, pending
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
async def _cancel_and_wait(fut, loop):
|
| 508 |
+
"""Cancel the *fut* future or task and wait until it completes."""
|
| 509 |
+
|
| 510 |
+
waiter = loop.create_future()
|
| 511 |
+
cb = functools.partial(_release_waiter, waiter)
|
| 512 |
+
fut.add_done_callback(cb)
|
| 513 |
+
|
| 514 |
+
try:
|
| 515 |
+
fut.cancel()
|
| 516 |
+
# We cannot wait on *fut* directly to make
|
| 517 |
+
# sure _cancel_and_wait itself is reliably cancellable.
|
| 518 |
+
await waiter
|
| 519 |
+
finally:
|
| 520 |
+
fut.remove_done_callback(cb)
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
# This is *not* a @coroutine! It is just an iterator (yielding Futures).
|
| 524 |
+
def as_completed(fs, *, timeout=None):
|
| 525 |
+
"""Return an iterator whose values are coroutines.
|
| 526 |
+
|
| 527 |
+
When waiting for the yielded coroutines you'll get the results (or
|
| 528 |
+
exceptions!) of the original Futures (or coroutines), in the order
|
| 529 |
+
in which and as soon as they complete.
|
| 530 |
+
|
| 531 |
+
This differs from PEP 3148; the proper way to use this is:
|
| 532 |
+
|
| 533 |
+
for f in as_completed(fs):
|
| 534 |
+
result = await f # The 'await' may raise.
|
| 535 |
+
# Use result.
|
| 536 |
+
|
| 537 |
+
If a timeout is specified, the 'await' will raise
|
| 538 |
+
TimeoutError when the timeout occurs before all Futures are done.
|
| 539 |
+
|
| 540 |
+
Note: The futures 'f' are not necessarily members of fs.
|
| 541 |
+
"""
|
| 542 |
+
if futures.isfuture(fs) or coroutines.iscoroutine(fs):
|
| 543 |
+
raise TypeError(f"expect an iterable of futures, not {type(fs).__name__}")
|
| 544 |
+
|
| 545 |
+
from .queues import Queue # Import here to avoid circular import problem.
|
| 546 |
+
done = Queue()
|
| 547 |
+
|
| 548 |
+
loop = events._get_event_loop()
|
| 549 |
+
todo = {ensure_future(f, loop=loop) for f in set(fs)}
|
| 550 |
+
timeout_handle = None
|
| 551 |
+
|
| 552 |
+
def _on_timeout():
|
| 553 |
+
for f in todo:
|
| 554 |
+
f.remove_done_callback(_on_completion)
|
| 555 |
+
done.put_nowait(None) # Queue a dummy value for _wait_for_one().
|
| 556 |
+
todo.clear() # Can't do todo.remove(f) in the loop.
|
| 557 |
+
|
| 558 |
+
def _on_completion(f):
|
| 559 |
+
if not todo:
|
| 560 |
+
return # _on_timeout() was here first.
|
| 561 |
+
todo.remove(f)
|
| 562 |
+
done.put_nowait(f)
|
| 563 |
+
if not todo and timeout_handle is not None:
|
| 564 |
+
timeout_handle.cancel()
|
| 565 |
+
|
| 566 |
+
async def _wait_for_one():
|
| 567 |
+
f = await done.get()
|
| 568 |
+
if f is None:
|
| 569 |
+
# Dummy value from _on_timeout().
|
| 570 |
+
raise exceptions.TimeoutError
|
| 571 |
+
return f.result() # May raise f.exception().
|
| 572 |
+
|
| 573 |
+
for f in todo:
|
| 574 |
+
f.add_done_callback(_on_completion)
|
| 575 |
+
if todo and timeout is not None:
|
| 576 |
+
timeout_handle = loop.call_later(timeout, _on_timeout)
|
| 577 |
+
for _ in range(len(todo)):
|
| 578 |
+
yield _wait_for_one()
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
@types.coroutine
|
| 582 |
+
def __sleep0():
|
| 583 |
+
"""Skip one event loop run cycle.
|
| 584 |
+
|
| 585 |
+
This is a private helper for 'asyncio.sleep()', used
|
| 586 |
+
when the 'delay' is set to 0. It uses a bare 'yield'
|
| 587 |
+
expression (which Task.__step knows how to handle)
|
| 588 |
+
instead of creating a Future object.
|
| 589 |
+
"""
|
| 590 |
+
yield
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
async def sleep(delay, result=None):
|
| 594 |
+
"""Coroutine that completes after a given time (in seconds)."""
|
| 595 |
+
if delay <= 0:
|
| 596 |
+
await __sleep0()
|
| 597 |
+
return result
|
| 598 |
+
|
| 599 |
+
loop = events.get_running_loop()
|
| 600 |
+
future = loop.create_future()
|
| 601 |
+
h = loop.call_later(delay,
|
| 602 |
+
futures._set_result_unless_cancelled,
|
| 603 |
+
future, result)
|
| 604 |
+
try:
|
| 605 |
+
return await future
|
| 606 |
+
finally:
|
| 607 |
+
h.cancel()
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def ensure_future(coro_or_future, *, loop=None):
|
| 611 |
+
"""Wrap a coroutine or an awaitable in a future.
|
| 612 |
+
|
| 613 |
+
If the argument is a Future, it is returned directly.
|
| 614 |
+
"""
|
| 615 |
+
return _ensure_future(coro_or_future, loop=loop)
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
def _ensure_future(coro_or_future, *, loop=None):
|
| 619 |
+
if futures.isfuture(coro_or_future):
|
| 620 |
+
if loop is not None and loop is not futures._get_loop(coro_or_future):
|
| 621 |
+
raise ValueError('The future belongs to a different loop than '
|
| 622 |
+
'the one specified as the loop argument')
|
| 623 |
+
return coro_or_future
|
| 624 |
+
called_wrap_awaitable = False
|
| 625 |
+
if not coroutines.iscoroutine(coro_or_future):
|
| 626 |
+
if inspect.isawaitable(coro_or_future):
|
| 627 |
+
coro_or_future = _wrap_awaitable(coro_or_future)
|
| 628 |
+
called_wrap_awaitable = True
|
| 629 |
+
else:
|
| 630 |
+
raise TypeError('An asyncio.Future, a coroutine or an awaitable '
|
| 631 |
+
'is required')
|
| 632 |
+
|
| 633 |
+
if loop is None:
|
| 634 |
+
loop = events._get_event_loop(stacklevel=4)
|
| 635 |
+
try:
|
| 636 |
+
return loop.create_task(coro_or_future)
|
| 637 |
+
except RuntimeError:
|
| 638 |
+
if not called_wrap_awaitable:
|
| 639 |
+
coro_or_future.close()
|
| 640 |
+
raise
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
@types.coroutine
|
| 644 |
+
def _wrap_awaitable(awaitable):
|
| 645 |
+
"""Helper for asyncio.ensure_future().
|
| 646 |
+
|
| 647 |
+
Wraps awaitable (an object with __await__) into a coroutine
|
| 648 |
+
that will later be wrapped in a Task by ensure_future().
|
| 649 |
+
"""
|
| 650 |
+
return (yield from awaitable.__await__())
|
| 651 |
+
|
| 652 |
+
_wrap_awaitable._is_coroutine = _is_coroutine
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
class _GatheringFuture(futures.Future):
|
| 656 |
+
"""Helper for gather().
|
| 657 |
+
|
| 658 |
+
This overrides cancel() to cancel all the children and act more
|
| 659 |
+
like Task.cancel(), which doesn't immediately mark itself as
|
| 660 |
+
cancelled.
|
| 661 |
+
"""
|
| 662 |
+
|
| 663 |
+
def __init__(self, children, *, loop):
|
| 664 |
+
assert loop is not None
|
| 665 |
+
super().__init__(loop=loop)
|
| 666 |
+
self._children = children
|
| 667 |
+
self._cancel_requested = False
|
| 668 |
+
|
| 669 |
+
def cancel(self, msg=None):
|
| 670 |
+
if self.done():
|
| 671 |
+
return False
|
| 672 |
+
ret = False
|
| 673 |
+
for child in self._children:
|
| 674 |
+
if child.cancel(msg=msg):
|
| 675 |
+
ret = True
|
| 676 |
+
if ret:
|
| 677 |
+
# If any child tasks were actually cancelled, we should
|
| 678 |
+
# propagate the cancellation request regardless of
|
| 679 |
+
# *return_exceptions* argument. See issue 32684.
|
| 680 |
+
self._cancel_requested = True
|
| 681 |
+
return ret
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def gather(*coros_or_futures, return_exceptions=False):
|
| 685 |
+
"""Return a future aggregating results from the given coroutines/futures.
|
| 686 |
+
|
| 687 |
+
Coroutines will be wrapped in a future and scheduled in the event
|
| 688 |
+
loop. They will not necessarily be scheduled in the same order as
|
| 689 |
+
passed in.
|
| 690 |
+
|
| 691 |
+
All futures must share the same event loop. If all the tasks are
|
| 692 |
+
done successfully, the returned future's result is the list of
|
| 693 |
+
results (in the order of the original sequence, not necessarily
|
| 694 |
+
the order of results arrival). If *return_exceptions* is True,
|
| 695 |
+
exceptions in the tasks are treated the same as successful
|
| 696 |
+
results, and gathered in the result list; otherwise, the first
|
| 697 |
+
raised exception will be immediately propagated to the returned
|
| 698 |
+
future.
|
| 699 |
+
|
| 700 |
+
Cancellation: if the outer Future is cancelled, all children (that
|
| 701 |
+
have not completed yet) are also cancelled. If any child is
|
| 702 |
+
cancelled, this is treated as if it raised CancelledError --
|
| 703 |
+
the outer Future is *not* cancelled in this case. (This is to
|
| 704 |
+
prevent the cancellation of one child to cause other children to
|
| 705 |
+
be cancelled.)
|
| 706 |
+
|
| 707 |
+
If *return_exceptions* is False, cancelling gather() after it
|
| 708 |
+
has been marked done won't cancel any submitted awaitables.
|
| 709 |
+
For instance, gather can be marked done after propagating an
|
| 710 |
+
exception to the caller, therefore, calling ``gather.cancel()``
|
| 711 |
+
after catching an exception (raised by one of the awaitables) from
|
| 712 |
+
gather won't cancel any other awaitables.
|
| 713 |
+
"""
|
| 714 |
+
if not coros_or_futures:
|
| 715 |
+
loop = events._get_event_loop()
|
| 716 |
+
outer = loop.create_future()
|
| 717 |
+
outer.set_result([])
|
| 718 |
+
return outer
|
| 719 |
+
|
| 720 |
+
def _done_callback(fut):
|
| 721 |
+
nonlocal nfinished
|
| 722 |
+
nfinished += 1
|
| 723 |
+
|
| 724 |
+
if outer is None or outer.done():
|
| 725 |
+
if not fut.cancelled():
|
| 726 |
+
# Mark exception retrieved.
|
| 727 |
+
fut.exception()
|
| 728 |
+
return
|
| 729 |
+
|
| 730 |
+
if not return_exceptions:
|
| 731 |
+
if fut.cancelled():
|
| 732 |
+
# Check if 'fut' is cancelled first, as
|
| 733 |
+
# 'fut.exception()' will *raise* a CancelledError
|
| 734 |
+
# instead of returning it.
|
| 735 |
+
exc = fut._make_cancelled_error()
|
| 736 |
+
outer.set_exception(exc)
|
| 737 |
+
return
|
| 738 |
+
else:
|
| 739 |
+
exc = fut.exception()
|
| 740 |
+
if exc is not None:
|
| 741 |
+
outer.set_exception(exc)
|
| 742 |
+
return
|
| 743 |
+
|
| 744 |
+
if nfinished == nfuts:
|
| 745 |
+
# All futures are done; create a list of results
|
| 746 |
+
# and set it to the 'outer' future.
|
| 747 |
+
results = []
|
| 748 |
+
|
| 749 |
+
for fut in children:
|
| 750 |
+
if fut.cancelled():
|
| 751 |
+
# Check if 'fut' is cancelled first, as 'fut.exception()'
|
| 752 |
+
# will *raise* a CancelledError instead of returning it.
|
| 753 |
+
# Also, since we're adding the exception return value
|
| 754 |
+
# to 'results' instead of raising it, don't bother
|
| 755 |
+
# setting __context__. This also lets us preserve
|
| 756 |
+
# calling '_make_cancelled_error()' at most once.
|
| 757 |
+
res = exceptions.CancelledError(
|
| 758 |
+
'' if fut._cancel_message is None else
|
| 759 |
+
fut._cancel_message)
|
| 760 |
+
else:
|
| 761 |
+
res = fut.exception()
|
| 762 |
+
if res is None:
|
| 763 |
+
res = fut.result()
|
| 764 |
+
results.append(res)
|
| 765 |
+
|
| 766 |
+
if outer._cancel_requested:
|
| 767 |
+
# If gather is being cancelled we must propagate the
|
| 768 |
+
# cancellation regardless of *return_exceptions* argument.
|
| 769 |
+
# See issue 32684.
|
| 770 |
+
exc = fut._make_cancelled_error()
|
| 771 |
+
outer.set_exception(exc)
|
| 772 |
+
else:
|
| 773 |
+
outer.set_result(results)
|
| 774 |
+
|
| 775 |
+
arg_to_fut = {}
|
| 776 |
+
children = []
|
| 777 |
+
nfuts = 0
|
| 778 |
+
nfinished = 0
|
| 779 |
+
loop = None
|
| 780 |
+
outer = None # bpo-46672
|
| 781 |
+
for arg in coros_or_futures:
|
| 782 |
+
if arg not in arg_to_fut:
|
| 783 |
+
fut = _ensure_future(arg, loop=loop)
|
| 784 |
+
if loop is None:
|
| 785 |
+
loop = futures._get_loop(fut)
|
| 786 |
+
if fut is not arg:
|
| 787 |
+
# 'arg' was not a Future, therefore, 'fut' is a new
|
| 788 |
+
# Future created specifically for 'arg'. Since the caller
|
| 789 |
+
# can't control it, disable the "destroy pending task"
|
| 790 |
+
# warning.
|
| 791 |
+
fut._log_destroy_pending = False
|
| 792 |
+
|
| 793 |
+
nfuts += 1
|
| 794 |
+
arg_to_fut[arg] = fut
|
| 795 |
+
fut.add_done_callback(_done_callback)
|
| 796 |
+
|
| 797 |
+
else:
|
| 798 |
+
# There's a duplicate Future object in coros_or_futures.
|
| 799 |
+
fut = arg_to_fut[arg]
|
| 800 |
+
|
| 801 |
+
children.append(fut)
|
| 802 |
+
|
| 803 |
+
outer = _GatheringFuture(children, loop=loop)
|
| 804 |
+
return outer
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
def shield(arg):
|
| 808 |
+
"""Wait for a future, shielding it from cancellation.
|
| 809 |
+
|
| 810 |
+
The statement
|
| 811 |
+
|
| 812 |
+
task = asyncio.create_task(something())
|
| 813 |
+
res = await shield(task)
|
| 814 |
+
|
| 815 |
+
is exactly equivalent to the statement
|
| 816 |
+
|
| 817 |
+
res = await something()
|
| 818 |
+
|
| 819 |
+
*except* that if the coroutine containing it is cancelled, the
|
| 820 |
+
task running in something() is not cancelled. From the POV of
|
| 821 |
+
something(), the cancellation did not happen. But its caller is
|
| 822 |
+
still cancelled, so the yield-from expression still raises
|
| 823 |
+
CancelledError. Note: If something() is cancelled by other means
|
| 824 |
+
this will still cancel shield().
|
| 825 |
+
|
| 826 |
+
If you want to completely ignore cancellation (not recommended)
|
| 827 |
+
you can combine shield() with a try/except clause, as follows:
|
| 828 |
+
|
| 829 |
+
task = asyncio.create_task(something())
|
| 830 |
+
try:
|
| 831 |
+
res = await shield(task)
|
| 832 |
+
except CancelledError:
|
| 833 |
+
res = None
|
| 834 |
+
|
| 835 |
+
Save a reference to tasks passed to this function, to avoid
|
| 836 |
+
a task disappearing mid-execution. The event loop only keeps
|
| 837 |
+
weak references to tasks. A task that isn't referenced elsewhere
|
| 838 |
+
may get garbage collected at any time, even before it's done.
|
| 839 |
+
"""
|
| 840 |
+
inner = _ensure_future(arg)
|
| 841 |
+
if inner.done():
|
| 842 |
+
# Shortcut.
|
| 843 |
+
return inner
|
| 844 |
+
loop = futures._get_loop(inner)
|
| 845 |
+
outer = loop.create_future()
|
| 846 |
+
|
| 847 |
+
def _inner_done_callback(inner):
|
| 848 |
+
if outer.cancelled():
|
| 849 |
+
if not inner.cancelled():
|
| 850 |
+
# Mark inner's result as retrieved.
|
| 851 |
+
inner.exception()
|
| 852 |
+
return
|
| 853 |
+
|
| 854 |
+
if inner.cancelled():
|
| 855 |
+
outer.cancel()
|
| 856 |
+
else:
|
| 857 |
+
exc = inner.exception()
|
| 858 |
+
if exc is not None:
|
| 859 |
+
outer.set_exception(exc)
|
| 860 |
+
else:
|
| 861 |
+
outer.set_result(inner.result())
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
def _outer_done_callback(outer):
|
| 865 |
+
if not inner.done():
|
| 866 |
+
inner.remove_done_callback(_inner_done_callback)
|
| 867 |
+
|
| 868 |
+
inner.add_done_callback(_inner_done_callback)
|
| 869 |
+
outer.add_done_callback(_outer_done_callback)
|
| 870 |
+
return outer
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
def run_coroutine_threadsafe(coro, loop):
|
| 874 |
+
"""Submit a coroutine object to a given event loop.
|
| 875 |
+
|
| 876 |
+
Return a concurrent.futures.Future to access the result.
|
| 877 |
+
"""
|
| 878 |
+
if not coroutines.iscoroutine(coro):
|
| 879 |
+
raise TypeError('A coroutine object is required')
|
| 880 |
+
future = concurrent.futures.Future()
|
| 881 |
+
|
| 882 |
+
def callback():
|
| 883 |
+
try:
|
| 884 |
+
futures._chain_future(ensure_future(coro, loop=loop), future)
|
| 885 |
+
except (SystemExit, KeyboardInterrupt):
|
| 886 |
+
raise
|
| 887 |
+
except BaseException as exc:
|
| 888 |
+
if future.set_running_or_notify_cancel():
|
| 889 |
+
future.set_exception(exc)
|
| 890 |
+
raise
|
| 891 |
+
|
| 892 |
+
loop.call_soon_threadsafe(callback)
|
| 893 |
+
return future
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
# WeakSet containing all alive tasks.
|
| 897 |
+
_all_tasks = weakref.WeakSet()
|
| 898 |
+
|
| 899 |
+
# Dictionary containing tasks that are currently active in
|
| 900 |
+
# all running event loops. {EventLoop: Task}
|
| 901 |
+
_current_tasks = {}
|
| 902 |
+
|
| 903 |
+
|
| 904 |
+
def _register_task(task):
|
| 905 |
+
"""Register a new task in asyncio as executed by loop."""
|
| 906 |
+
_all_tasks.add(task)
|
| 907 |
+
|
| 908 |
+
|
| 909 |
+
def _enter_task(loop, task):
|
| 910 |
+
current_task = _current_tasks.get(loop)
|
| 911 |
+
if current_task is not None:
|
| 912 |
+
raise RuntimeError(f"Cannot enter into task {task!r} while another "
|
| 913 |
+
f"task {current_task!r} is being executed.")
|
| 914 |
+
_current_tasks[loop] = task
|
| 915 |
+
|
| 916 |
+
|
| 917 |
+
def _leave_task(loop, task):
|
| 918 |
+
current_task = _current_tasks.get(loop)
|
| 919 |
+
if current_task is not task:
|
| 920 |
+
raise RuntimeError(f"Leaving task {task!r} does not match "
|
| 921 |
+
f"the current task {current_task!r}.")
|
| 922 |
+
del _current_tasks[loop]
|
| 923 |
+
|
| 924 |
+
|
| 925 |
+
def _unregister_task(task):
|
| 926 |
+
"""Unregister a task."""
|
| 927 |
+
_all_tasks.discard(task)
|
| 928 |
+
|
| 929 |
+
|
| 930 |
+
_py_register_task = _register_task
|
| 931 |
+
_py_unregister_task = _unregister_task
|
| 932 |
+
_py_enter_task = _enter_task
|
| 933 |
+
_py_leave_task = _leave_task
|
| 934 |
+
|
| 935 |
+
|
| 936 |
+
try:
|
| 937 |
+
from _asyncio import (_register_task, _unregister_task,
|
| 938 |
+
_enter_task, _leave_task,
|
| 939 |
+
_all_tasks, _current_tasks)
|
| 940 |
+
except ImportError:
|
| 941 |
+
pass
|
| 942 |
+
else:
|
| 943 |
+
_c_register_task = _register_task
|
| 944 |
+
_c_unregister_task = _unregister_task
|
| 945 |
+
_c_enter_task = _enter_task
|
| 946 |
+
_c_leave_task = _leave_task
|
janus/lib/python3.10/asyncio/threads.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""High-level support for working with threads in asyncio"""
|
| 2 |
+
|
| 3 |
+
import functools
|
| 4 |
+
import contextvars
|
| 5 |
+
|
| 6 |
+
from . import events
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
__all__ = "to_thread",
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
async def to_thread(func, /, *args, **kwargs):
|
| 13 |
+
"""Asynchronously run function *func* in a separate thread.
|
| 14 |
+
|
| 15 |
+
Any *args and **kwargs supplied for this function are directly passed
|
| 16 |
+
to *func*. Also, the current :class:`contextvars.Context` is propagated,
|
| 17 |
+
allowing context variables from the main thread to be accessed in the
|
| 18 |
+
separate thread.
|
| 19 |
+
|
| 20 |
+
Return a coroutine that can be awaited to get the eventual result of *func*.
|
| 21 |
+
"""
|
| 22 |
+
loop = events.get_running_loop()
|
| 23 |
+
ctx = contextvars.copy_context()
|
| 24 |
+
func_call = functools.partial(ctx.run, func, *args, **kwargs)
|
| 25 |
+
return await loop.run_in_executor(None, func_call)
|
janus/lib/python3.10/asyncio/windows_events.py
ADDED
|
@@ -0,0 +1,924 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Selector and proactor event loops for Windows."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
if sys.platform != 'win32': # pragma: no cover
|
| 6 |
+
raise ImportError('win32 only')
|
| 7 |
+
|
| 8 |
+
import _overlapped
|
| 9 |
+
import _winapi
|
| 10 |
+
import errno
|
| 11 |
+
import math
|
| 12 |
+
import msvcrt
|
| 13 |
+
import socket
|
| 14 |
+
import struct
|
| 15 |
+
import time
|
| 16 |
+
import weakref
|
| 17 |
+
|
| 18 |
+
from . import events
|
| 19 |
+
from . import base_subprocess
|
| 20 |
+
from . import futures
|
| 21 |
+
from . import exceptions
|
| 22 |
+
from . import proactor_events
|
| 23 |
+
from . import selector_events
|
| 24 |
+
from . import tasks
|
| 25 |
+
from . import windows_utils
|
| 26 |
+
from .log import logger
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
__all__ = (
|
| 30 |
+
'SelectorEventLoop', 'ProactorEventLoop', 'IocpProactor',
|
| 31 |
+
'DefaultEventLoopPolicy', 'WindowsSelectorEventLoopPolicy',
|
| 32 |
+
'WindowsProactorEventLoopPolicy',
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
NULL = 0
|
| 37 |
+
INFINITE = 0xffffffff
|
| 38 |
+
ERROR_CONNECTION_REFUSED = 1225
|
| 39 |
+
ERROR_CONNECTION_ABORTED = 1236
|
| 40 |
+
|
| 41 |
+
# Initial delay in seconds for connect_pipe() before retrying to connect
|
| 42 |
+
CONNECT_PIPE_INIT_DELAY = 0.001
|
| 43 |
+
|
| 44 |
+
# Maximum delay in seconds for connect_pipe() before retrying to connect
|
| 45 |
+
CONNECT_PIPE_MAX_DELAY = 0.100
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class _OverlappedFuture(futures.Future):
|
| 49 |
+
"""Subclass of Future which represents an overlapped operation.
|
| 50 |
+
|
| 51 |
+
Cancelling it will immediately cancel the overlapped operation.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
def __init__(self, ov, *, loop=None):
|
| 55 |
+
super().__init__(loop=loop)
|
| 56 |
+
if self._source_traceback:
|
| 57 |
+
del self._source_traceback[-1]
|
| 58 |
+
self._ov = ov
|
| 59 |
+
|
| 60 |
+
def _repr_info(self):
|
| 61 |
+
info = super()._repr_info()
|
| 62 |
+
if self._ov is not None:
|
| 63 |
+
state = 'pending' if self._ov.pending else 'completed'
|
| 64 |
+
info.insert(1, f'overlapped=<{state}, {self._ov.address:#x}>')
|
| 65 |
+
return info
|
| 66 |
+
|
| 67 |
+
def _cancel_overlapped(self):
|
| 68 |
+
if self._ov is None:
|
| 69 |
+
return
|
| 70 |
+
try:
|
| 71 |
+
self._ov.cancel()
|
| 72 |
+
except OSError as exc:
|
| 73 |
+
context = {
|
| 74 |
+
'message': 'Cancelling an overlapped future failed',
|
| 75 |
+
'exception': exc,
|
| 76 |
+
'future': self,
|
| 77 |
+
}
|
| 78 |
+
if self._source_traceback:
|
| 79 |
+
context['source_traceback'] = self._source_traceback
|
| 80 |
+
self._loop.call_exception_handler(context)
|
| 81 |
+
self._ov = None
|
| 82 |
+
|
| 83 |
+
def cancel(self, msg=None):
|
| 84 |
+
self._cancel_overlapped()
|
| 85 |
+
return super().cancel(msg=msg)
|
| 86 |
+
|
| 87 |
+
def set_exception(self, exception):
|
| 88 |
+
super().set_exception(exception)
|
| 89 |
+
self._cancel_overlapped()
|
| 90 |
+
|
| 91 |
+
def set_result(self, result):
|
| 92 |
+
super().set_result(result)
|
| 93 |
+
self._ov = None
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class _BaseWaitHandleFuture(futures.Future):
|
| 97 |
+
"""Subclass of Future which represents a wait handle."""
|
| 98 |
+
|
| 99 |
+
def __init__(self, ov, handle, wait_handle, *, loop=None):
|
| 100 |
+
super().__init__(loop=loop)
|
| 101 |
+
if self._source_traceback:
|
| 102 |
+
del self._source_traceback[-1]
|
| 103 |
+
# Keep a reference to the Overlapped object to keep it alive until the
|
| 104 |
+
# wait is unregistered
|
| 105 |
+
self._ov = ov
|
| 106 |
+
self._handle = handle
|
| 107 |
+
self._wait_handle = wait_handle
|
| 108 |
+
|
| 109 |
+
# Should we call UnregisterWaitEx() if the wait completes
|
| 110 |
+
# or is cancelled?
|
| 111 |
+
self._registered = True
|
| 112 |
+
|
| 113 |
+
def _poll(self):
|
| 114 |
+
# non-blocking wait: use a timeout of 0 millisecond
|
| 115 |
+
return (_winapi.WaitForSingleObject(self._handle, 0) ==
|
| 116 |
+
_winapi.WAIT_OBJECT_0)
|
| 117 |
+
|
| 118 |
+
def _repr_info(self):
|
| 119 |
+
info = super()._repr_info()
|
| 120 |
+
info.append(f'handle={self._handle:#x}')
|
| 121 |
+
if self._handle is not None:
|
| 122 |
+
state = 'signaled' if self._poll() else 'waiting'
|
| 123 |
+
info.append(state)
|
| 124 |
+
if self._wait_handle is not None:
|
| 125 |
+
info.append(f'wait_handle={self._wait_handle:#x}')
|
| 126 |
+
return info
|
| 127 |
+
|
| 128 |
+
def _unregister_wait_cb(self, fut):
|
| 129 |
+
# The wait was unregistered: it's not safe to destroy the Overlapped
|
| 130 |
+
# object
|
| 131 |
+
self._ov = None
|
| 132 |
+
|
| 133 |
+
def _unregister_wait(self):
|
| 134 |
+
if not self._registered:
|
| 135 |
+
return
|
| 136 |
+
self._registered = False
|
| 137 |
+
|
| 138 |
+
wait_handle = self._wait_handle
|
| 139 |
+
self._wait_handle = None
|
| 140 |
+
try:
|
| 141 |
+
_overlapped.UnregisterWait(wait_handle)
|
| 142 |
+
except OSError as exc:
|
| 143 |
+
if exc.winerror != _overlapped.ERROR_IO_PENDING:
|
| 144 |
+
context = {
|
| 145 |
+
'message': 'Failed to unregister the wait handle',
|
| 146 |
+
'exception': exc,
|
| 147 |
+
'future': self,
|
| 148 |
+
}
|
| 149 |
+
if self._source_traceback:
|
| 150 |
+
context['source_traceback'] = self._source_traceback
|
| 151 |
+
self._loop.call_exception_handler(context)
|
| 152 |
+
return
|
| 153 |
+
# ERROR_IO_PENDING means that the unregister is pending
|
| 154 |
+
|
| 155 |
+
self._unregister_wait_cb(None)
|
| 156 |
+
|
| 157 |
+
def cancel(self, msg=None):
|
| 158 |
+
self._unregister_wait()
|
| 159 |
+
return super().cancel(msg=msg)
|
| 160 |
+
|
| 161 |
+
def set_exception(self, exception):
|
| 162 |
+
self._unregister_wait()
|
| 163 |
+
super().set_exception(exception)
|
| 164 |
+
|
| 165 |
+
def set_result(self, result):
|
| 166 |
+
self._unregister_wait()
|
| 167 |
+
super().set_result(result)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
class _WaitCancelFuture(_BaseWaitHandleFuture):
|
| 171 |
+
"""Subclass of Future which represents a wait for the cancellation of a
|
| 172 |
+
_WaitHandleFuture using an event.
|
| 173 |
+
"""
|
| 174 |
+
|
| 175 |
+
def __init__(self, ov, event, wait_handle, *, loop=None):
|
| 176 |
+
super().__init__(ov, event, wait_handle, loop=loop)
|
| 177 |
+
|
| 178 |
+
self._done_callback = None
|
| 179 |
+
|
| 180 |
+
def cancel(self):
|
| 181 |
+
raise RuntimeError("_WaitCancelFuture must not be cancelled")
|
| 182 |
+
|
| 183 |
+
def set_result(self, result):
|
| 184 |
+
super().set_result(result)
|
| 185 |
+
if self._done_callback is not None:
|
| 186 |
+
self._done_callback(self)
|
| 187 |
+
|
| 188 |
+
def set_exception(self, exception):
|
| 189 |
+
super().set_exception(exception)
|
| 190 |
+
if self._done_callback is not None:
|
| 191 |
+
self._done_callback(self)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class _WaitHandleFuture(_BaseWaitHandleFuture):
|
| 195 |
+
def __init__(self, ov, handle, wait_handle, proactor, *, loop=None):
|
| 196 |
+
super().__init__(ov, handle, wait_handle, loop=loop)
|
| 197 |
+
self._proactor = proactor
|
| 198 |
+
self._unregister_proactor = True
|
| 199 |
+
self._event = _overlapped.CreateEvent(None, True, False, None)
|
| 200 |
+
self._event_fut = None
|
| 201 |
+
|
| 202 |
+
def _unregister_wait_cb(self, fut):
|
| 203 |
+
if self._event is not None:
|
| 204 |
+
_winapi.CloseHandle(self._event)
|
| 205 |
+
self._event = None
|
| 206 |
+
self._event_fut = None
|
| 207 |
+
|
| 208 |
+
# If the wait was cancelled, the wait may never be signalled, so
|
| 209 |
+
# it's required to unregister it. Otherwise, IocpProactor.close() will
|
| 210 |
+
# wait forever for an event which will never come.
|
| 211 |
+
#
|
| 212 |
+
# If the IocpProactor already received the event, it's safe to call
|
| 213 |
+
# _unregister() because we kept a reference to the Overlapped object
|
| 214 |
+
# which is used as a unique key.
|
| 215 |
+
self._proactor._unregister(self._ov)
|
| 216 |
+
self._proactor = None
|
| 217 |
+
|
| 218 |
+
super()._unregister_wait_cb(fut)
|
| 219 |
+
|
| 220 |
+
def _unregister_wait(self):
|
| 221 |
+
if not self._registered:
|
| 222 |
+
return
|
| 223 |
+
self._registered = False
|
| 224 |
+
|
| 225 |
+
wait_handle = self._wait_handle
|
| 226 |
+
self._wait_handle = None
|
| 227 |
+
try:
|
| 228 |
+
_overlapped.UnregisterWaitEx(wait_handle, self._event)
|
| 229 |
+
except OSError as exc:
|
| 230 |
+
if exc.winerror != _overlapped.ERROR_IO_PENDING:
|
| 231 |
+
context = {
|
| 232 |
+
'message': 'Failed to unregister the wait handle',
|
| 233 |
+
'exception': exc,
|
| 234 |
+
'future': self,
|
| 235 |
+
}
|
| 236 |
+
if self._source_traceback:
|
| 237 |
+
context['source_traceback'] = self._source_traceback
|
| 238 |
+
self._loop.call_exception_handler(context)
|
| 239 |
+
return
|
| 240 |
+
# ERROR_IO_PENDING is not an error, the wait was unregistered
|
| 241 |
+
|
| 242 |
+
self._event_fut = self._proactor._wait_cancel(self._event,
|
| 243 |
+
self._unregister_wait_cb)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
class PipeServer(object):
|
| 247 |
+
"""Class representing a pipe server.
|
| 248 |
+
|
| 249 |
+
This is much like a bound, listening socket.
|
| 250 |
+
"""
|
| 251 |
+
def __init__(self, address):
|
| 252 |
+
self._address = address
|
| 253 |
+
self._free_instances = weakref.WeakSet()
|
| 254 |
+
# initialize the pipe attribute before calling _server_pipe_handle()
|
| 255 |
+
# because this function can raise an exception and the destructor calls
|
| 256 |
+
# the close() method
|
| 257 |
+
self._pipe = None
|
| 258 |
+
self._accept_pipe_future = None
|
| 259 |
+
self._pipe = self._server_pipe_handle(True)
|
| 260 |
+
|
| 261 |
+
def _get_unconnected_pipe(self):
|
| 262 |
+
# Create new instance and return previous one. This ensures
|
| 263 |
+
# that (until the server is closed) there is always at least
|
| 264 |
+
# one pipe handle for address. Therefore if a client attempt
|
| 265 |
+
# to connect it will not fail with FileNotFoundError.
|
| 266 |
+
tmp, self._pipe = self._pipe, self._server_pipe_handle(False)
|
| 267 |
+
return tmp
|
| 268 |
+
|
| 269 |
+
def _server_pipe_handle(self, first):
|
| 270 |
+
# Return a wrapper for a new pipe handle.
|
| 271 |
+
if self.closed():
|
| 272 |
+
return None
|
| 273 |
+
flags = _winapi.PIPE_ACCESS_DUPLEX | _winapi.FILE_FLAG_OVERLAPPED
|
| 274 |
+
if first:
|
| 275 |
+
flags |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE
|
| 276 |
+
h = _winapi.CreateNamedPipe(
|
| 277 |
+
self._address, flags,
|
| 278 |
+
_winapi.PIPE_TYPE_MESSAGE | _winapi.PIPE_READMODE_MESSAGE |
|
| 279 |
+
_winapi.PIPE_WAIT,
|
| 280 |
+
_winapi.PIPE_UNLIMITED_INSTANCES,
|
| 281 |
+
windows_utils.BUFSIZE, windows_utils.BUFSIZE,
|
| 282 |
+
_winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL)
|
| 283 |
+
pipe = windows_utils.PipeHandle(h)
|
| 284 |
+
self._free_instances.add(pipe)
|
| 285 |
+
return pipe
|
| 286 |
+
|
| 287 |
+
def closed(self):
|
| 288 |
+
return (self._address is None)
|
| 289 |
+
|
| 290 |
+
def close(self):
|
| 291 |
+
if self._accept_pipe_future is not None:
|
| 292 |
+
self._accept_pipe_future.cancel()
|
| 293 |
+
self._accept_pipe_future = None
|
| 294 |
+
# Close all instances which have not been connected to by a client.
|
| 295 |
+
if self._address is not None:
|
| 296 |
+
for pipe in self._free_instances:
|
| 297 |
+
pipe.close()
|
| 298 |
+
self._pipe = None
|
| 299 |
+
self._address = None
|
| 300 |
+
self._free_instances.clear()
|
| 301 |
+
|
| 302 |
+
__del__ = close
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
class _WindowsSelectorEventLoop(selector_events.BaseSelectorEventLoop):
|
| 306 |
+
"""Windows version of selector event loop."""
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
class ProactorEventLoop(proactor_events.BaseProactorEventLoop):
|
| 310 |
+
"""Windows version of proactor event loop using IOCP."""
|
| 311 |
+
|
| 312 |
+
def __init__(self, proactor=None):
|
| 313 |
+
if proactor is None:
|
| 314 |
+
proactor = IocpProactor()
|
| 315 |
+
super().__init__(proactor)
|
| 316 |
+
|
| 317 |
+
def run_forever(self):
|
| 318 |
+
try:
|
| 319 |
+
assert self._self_reading_future is None
|
| 320 |
+
self.call_soon(self._loop_self_reading)
|
| 321 |
+
super().run_forever()
|
| 322 |
+
finally:
|
| 323 |
+
if self._self_reading_future is not None:
|
| 324 |
+
ov = self._self_reading_future._ov
|
| 325 |
+
self._self_reading_future.cancel()
|
| 326 |
+
# self_reading_future always uses IOCP, so even though it's
|
| 327 |
+
# been cancelled, we need to make sure that the IOCP message
|
| 328 |
+
# is received so that the kernel is not holding on to the
|
| 329 |
+
# memory, possibly causing memory corruption later. Only
|
| 330 |
+
# unregister it if IO is complete in all respects. Otherwise
|
| 331 |
+
# we need another _poll() later to complete the IO.
|
| 332 |
+
if ov is not None and not ov.pending:
|
| 333 |
+
self._proactor._unregister(ov)
|
| 334 |
+
self._self_reading_future = None
|
| 335 |
+
|
| 336 |
+
async def create_pipe_connection(self, protocol_factory, address):
|
| 337 |
+
f = self._proactor.connect_pipe(address)
|
| 338 |
+
pipe = await f
|
| 339 |
+
protocol = protocol_factory()
|
| 340 |
+
trans = self._make_duplex_pipe_transport(pipe, protocol,
|
| 341 |
+
extra={'addr': address})
|
| 342 |
+
return trans, protocol
|
| 343 |
+
|
| 344 |
+
async def start_serving_pipe(self, protocol_factory, address):
|
| 345 |
+
server = PipeServer(address)
|
| 346 |
+
|
| 347 |
+
def loop_accept_pipe(f=None):
|
| 348 |
+
pipe = None
|
| 349 |
+
try:
|
| 350 |
+
if f:
|
| 351 |
+
pipe = f.result()
|
| 352 |
+
server._free_instances.discard(pipe)
|
| 353 |
+
|
| 354 |
+
if server.closed():
|
| 355 |
+
# A client connected before the server was closed:
|
| 356 |
+
# drop the client (close the pipe) and exit
|
| 357 |
+
pipe.close()
|
| 358 |
+
return
|
| 359 |
+
|
| 360 |
+
protocol = protocol_factory()
|
| 361 |
+
self._make_duplex_pipe_transport(
|
| 362 |
+
pipe, protocol, extra={'addr': address})
|
| 363 |
+
|
| 364 |
+
pipe = server._get_unconnected_pipe()
|
| 365 |
+
if pipe is None:
|
| 366 |
+
return
|
| 367 |
+
|
| 368 |
+
f = self._proactor.accept_pipe(pipe)
|
| 369 |
+
except BrokenPipeError:
|
| 370 |
+
if pipe and pipe.fileno() != -1:
|
| 371 |
+
pipe.close()
|
| 372 |
+
self.call_soon(loop_accept_pipe)
|
| 373 |
+
except OSError as exc:
|
| 374 |
+
if pipe and pipe.fileno() != -1:
|
| 375 |
+
self.call_exception_handler({
|
| 376 |
+
'message': 'Pipe accept failed',
|
| 377 |
+
'exception': exc,
|
| 378 |
+
'pipe': pipe,
|
| 379 |
+
})
|
| 380 |
+
pipe.close()
|
| 381 |
+
elif self._debug:
|
| 382 |
+
logger.warning("Accept pipe failed on pipe %r",
|
| 383 |
+
pipe, exc_info=True)
|
| 384 |
+
self.call_soon(loop_accept_pipe)
|
| 385 |
+
except exceptions.CancelledError:
|
| 386 |
+
if pipe:
|
| 387 |
+
pipe.close()
|
| 388 |
+
else:
|
| 389 |
+
server._accept_pipe_future = f
|
| 390 |
+
f.add_done_callback(loop_accept_pipe)
|
| 391 |
+
|
| 392 |
+
self.call_soon(loop_accept_pipe)
|
| 393 |
+
return [server]
|
| 394 |
+
|
| 395 |
+
async def _make_subprocess_transport(self, protocol, args, shell,
|
| 396 |
+
stdin, stdout, stderr, bufsize,
|
| 397 |
+
extra=None, **kwargs):
|
| 398 |
+
waiter = self.create_future()
|
| 399 |
+
transp = _WindowsSubprocessTransport(self, protocol, args, shell,
|
| 400 |
+
stdin, stdout, stderr, bufsize,
|
| 401 |
+
waiter=waiter, extra=extra,
|
| 402 |
+
**kwargs)
|
| 403 |
+
try:
|
| 404 |
+
await waiter
|
| 405 |
+
except (SystemExit, KeyboardInterrupt):
|
| 406 |
+
raise
|
| 407 |
+
except BaseException:
|
| 408 |
+
transp.close()
|
| 409 |
+
await transp._wait()
|
| 410 |
+
raise
|
| 411 |
+
|
| 412 |
+
return transp
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
class IocpProactor:
|
| 416 |
+
"""Proactor implementation using IOCP."""
|
| 417 |
+
|
| 418 |
+
def __init__(self, concurrency=0xffffffff):
|
| 419 |
+
self._loop = None
|
| 420 |
+
self._results = []
|
| 421 |
+
self._iocp = _overlapped.CreateIoCompletionPort(
|
| 422 |
+
_overlapped.INVALID_HANDLE_VALUE, NULL, 0, concurrency)
|
| 423 |
+
self._cache = {}
|
| 424 |
+
self._registered = weakref.WeakSet()
|
| 425 |
+
self._unregistered = []
|
| 426 |
+
self._stopped_serving = weakref.WeakSet()
|
| 427 |
+
|
| 428 |
+
def _check_closed(self):
|
| 429 |
+
if self._iocp is None:
|
| 430 |
+
raise RuntimeError('IocpProactor is closed')
|
| 431 |
+
|
| 432 |
+
def __repr__(self):
|
| 433 |
+
info = ['overlapped#=%s' % len(self._cache),
|
| 434 |
+
'result#=%s' % len(self._results)]
|
| 435 |
+
if self._iocp is None:
|
| 436 |
+
info.append('closed')
|
| 437 |
+
return '<%s %s>' % (self.__class__.__name__, " ".join(info))
|
| 438 |
+
|
| 439 |
+
def set_loop(self, loop):
|
| 440 |
+
self._loop = loop
|
| 441 |
+
|
| 442 |
+
def select(self, timeout=None):
|
| 443 |
+
if not self._results:
|
| 444 |
+
self._poll(timeout)
|
| 445 |
+
tmp = self._results
|
| 446 |
+
self._results = []
|
| 447 |
+
try:
|
| 448 |
+
return tmp
|
| 449 |
+
finally:
|
| 450 |
+
# Needed to break cycles when an exception occurs.
|
| 451 |
+
tmp = None
|
| 452 |
+
|
| 453 |
+
def _result(self, value):
|
| 454 |
+
fut = self._loop.create_future()
|
| 455 |
+
fut.set_result(value)
|
| 456 |
+
return fut
|
| 457 |
+
|
| 458 |
+
def recv(self, conn, nbytes, flags=0):
|
| 459 |
+
self._register_with_iocp(conn)
|
| 460 |
+
ov = _overlapped.Overlapped(NULL)
|
| 461 |
+
try:
|
| 462 |
+
if isinstance(conn, socket.socket):
|
| 463 |
+
ov.WSARecv(conn.fileno(), nbytes, flags)
|
| 464 |
+
else:
|
| 465 |
+
ov.ReadFile(conn.fileno(), nbytes)
|
| 466 |
+
except BrokenPipeError:
|
| 467 |
+
return self._result(b'')
|
| 468 |
+
|
| 469 |
+
def finish_recv(trans, key, ov):
|
| 470 |
+
try:
|
| 471 |
+
return ov.getresult()
|
| 472 |
+
except OSError as exc:
|
| 473 |
+
if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
|
| 474 |
+
_overlapped.ERROR_OPERATION_ABORTED):
|
| 475 |
+
raise ConnectionResetError(*exc.args)
|
| 476 |
+
else:
|
| 477 |
+
raise
|
| 478 |
+
|
| 479 |
+
return self._register(ov, conn, finish_recv)
|
| 480 |
+
|
| 481 |
+
def recv_into(self, conn, buf, flags=0):
|
| 482 |
+
self._register_with_iocp(conn)
|
| 483 |
+
ov = _overlapped.Overlapped(NULL)
|
| 484 |
+
try:
|
| 485 |
+
if isinstance(conn, socket.socket):
|
| 486 |
+
ov.WSARecvInto(conn.fileno(), buf, flags)
|
| 487 |
+
else:
|
| 488 |
+
ov.ReadFileInto(conn.fileno(), buf)
|
| 489 |
+
except BrokenPipeError:
|
| 490 |
+
return self._result(0)
|
| 491 |
+
|
| 492 |
+
def finish_recv(trans, key, ov):
|
| 493 |
+
try:
|
| 494 |
+
return ov.getresult()
|
| 495 |
+
except OSError as exc:
|
| 496 |
+
if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
|
| 497 |
+
_overlapped.ERROR_OPERATION_ABORTED):
|
| 498 |
+
raise ConnectionResetError(*exc.args)
|
| 499 |
+
else:
|
| 500 |
+
raise
|
| 501 |
+
|
| 502 |
+
return self._register(ov, conn, finish_recv)
|
| 503 |
+
|
| 504 |
+
def recvfrom(self, conn, nbytes, flags=0):
|
| 505 |
+
self._register_with_iocp(conn)
|
| 506 |
+
ov = _overlapped.Overlapped(NULL)
|
| 507 |
+
try:
|
| 508 |
+
ov.WSARecvFrom(conn.fileno(), nbytes, flags)
|
| 509 |
+
except BrokenPipeError:
|
| 510 |
+
return self._result((b'', None))
|
| 511 |
+
|
| 512 |
+
def finish_recv(trans, key, ov):
|
| 513 |
+
try:
|
| 514 |
+
return ov.getresult()
|
| 515 |
+
except OSError as exc:
|
| 516 |
+
if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
|
| 517 |
+
_overlapped.ERROR_OPERATION_ABORTED):
|
| 518 |
+
raise ConnectionResetError(*exc.args)
|
| 519 |
+
else:
|
| 520 |
+
raise
|
| 521 |
+
|
| 522 |
+
return self._register(ov, conn, finish_recv)
|
| 523 |
+
|
| 524 |
+
def sendto(self, conn, buf, flags=0, addr=None):
|
| 525 |
+
self._register_with_iocp(conn)
|
| 526 |
+
ov = _overlapped.Overlapped(NULL)
|
| 527 |
+
|
| 528 |
+
ov.WSASendTo(conn.fileno(), buf, flags, addr)
|
| 529 |
+
|
| 530 |
+
def finish_send(trans, key, ov):
|
| 531 |
+
try:
|
| 532 |
+
return ov.getresult()
|
| 533 |
+
except OSError as exc:
|
| 534 |
+
if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
|
| 535 |
+
_overlapped.ERROR_OPERATION_ABORTED):
|
| 536 |
+
raise ConnectionResetError(*exc.args)
|
| 537 |
+
else:
|
| 538 |
+
raise
|
| 539 |
+
|
| 540 |
+
return self._register(ov, conn, finish_send)
|
| 541 |
+
|
| 542 |
+
def send(self, conn, buf, flags=0):
|
| 543 |
+
self._register_with_iocp(conn)
|
| 544 |
+
ov = _overlapped.Overlapped(NULL)
|
| 545 |
+
if isinstance(conn, socket.socket):
|
| 546 |
+
ov.WSASend(conn.fileno(), buf, flags)
|
| 547 |
+
else:
|
| 548 |
+
ov.WriteFile(conn.fileno(), buf)
|
| 549 |
+
|
| 550 |
+
def finish_send(trans, key, ov):
|
| 551 |
+
try:
|
| 552 |
+
return ov.getresult()
|
| 553 |
+
except OSError as exc:
|
| 554 |
+
if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
|
| 555 |
+
_overlapped.ERROR_OPERATION_ABORTED):
|
| 556 |
+
raise ConnectionResetError(*exc.args)
|
| 557 |
+
else:
|
| 558 |
+
raise
|
| 559 |
+
|
| 560 |
+
return self._register(ov, conn, finish_send)
|
| 561 |
+
|
| 562 |
+
def accept(self, listener):
|
| 563 |
+
self._register_with_iocp(listener)
|
| 564 |
+
conn = self._get_accept_socket(listener.family)
|
| 565 |
+
ov = _overlapped.Overlapped(NULL)
|
| 566 |
+
ov.AcceptEx(listener.fileno(), conn.fileno())
|
| 567 |
+
|
| 568 |
+
def finish_accept(trans, key, ov):
|
| 569 |
+
ov.getresult()
|
| 570 |
+
# Use SO_UPDATE_ACCEPT_CONTEXT so getsockname() etc work.
|
| 571 |
+
buf = struct.pack('@P', listener.fileno())
|
| 572 |
+
conn.setsockopt(socket.SOL_SOCKET,
|
| 573 |
+
_overlapped.SO_UPDATE_ACCEPT_CONTEXT, buf)
|
| 574 |
+
conn.settimeout(listener.gettimeout())
|
| 575 |
+
return conn, conn.getpeername()
|
| 576 |
+
|
| 577 |
+
async def accept_coro(future, conn):
|
| 578 |
+
# Coroutine closing the accept socket if the future is cancelled
|
| 579 |
+
try:
|
| 580 |
+
await future
|
| 581 |
+
except exceptions.CancelledError:
|
| 582 |
+
conn.close()
|
| 583 |
+
raise
|
| 584 |
+
|
| 585 |
+
future = self._register(ov, listener, finish_accept)
|
| 586 |
+
coro = accept_coro(future, conn)
|
| 587 |
+
tasks.ensure_future(coro, loop=self._loop)
|
| 588 |
+
return future
|
| 589 |
+
|
| 590 |
+
def connect(self, conn, address):
|
| 591 |
+
if conn.type == socket.SOCK_DGRAM:
|
| 592 |
+
# WSAConnect will complete immediately for UDP sockets so we don't
|
| 593 |
+
# need to register any IOCP operation
|
| 594 |
+
_overlapped.WSAConnect(conn.fileno(), address)
|
| 595 |
+
fut = self._loop.create_future()
|
| 596 |
+
fut.set_result(None)
|
| 597 |
+
return fut
|
| 598 |
+
|
| 599 |
+
self._register_with_iocp(conn)
|
| 600 |
+
# The socket needs to be locally bound before we call ConnectEx().
|
| 601 |
+
try:
|
| 602 |
+
_overlapped.BindLocal(conn.fileno(), conn.family)
|
| 603 |
+
except OSError as e:
|
| 604 |
+
if e.winerror != errno.WSAEINVAL:
|
| 605 |
+
raise
|
| 606 |
+
# Probably already locally bound; check using getsockname().
|
| 607 |
+
if conn.getsockname()[1] == 0:
|
| 608 |
+
raise
|
| 609 |
+
ov = _overlapped.Overlapped(NULL)
|
| 610 |
+
ov.ConnectEx(conn.fileno(), address)
|
| 611 |
+
|
| 612 |
+
def finish_connect(trans, key, ov):
|
| 613 |
+
ov.getresult()
|
| 614 |
+
# Use SO_UPDATE_CONNECT_CONTEXT so getsockname() etc work.
|
| 615 |
+
conn.setsockopt(socket.SOL_SOCKET,
|
| 616 |
+
_overlapped.SO_UPDATE_CONNECT_CONTEXT, 0)
|
| 617 |
+
return conn
|
| 618 |
+
|
| 619 |
+
return self._register(ov, conn, finish_connect)
|
| 620 |
+
|
| 621 |
+
def sendfile(self, sock, file, offset, count):
|
| 622 |
+
self._register_with_iocp(sock)
|
| 623 |
+
ov = _overlapped.Overlapped(NULL)
|
| 624 |
+
offset_low = offset & 0xffff_ffff
|
| 625 |
+
offset_high = (offset >> 32) & 0xffff_ffff
|
| 626 |
+
ov.TransmitFile(sock.fileno(),
|
| 627 |
+
msvcrt.get_osfhandle(file.fileno()),
|
| 628 |
+
offset_low, offset_high,
|
| 629 |
+
count, 0, 0)
|
| 630 |
+
|
| 631 |
+
def finish_sendfile(trans, key, ov):
|
| 632 |
+
try:
|
| 633 |
+
return ov.getresult()
|
| 634 |
+
except OSError as exc:
|
| 635 |
+
if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
|
| 636 |
+
_overlapped.ERROR_OPERATION_ABORTED):
|
| 637 |
+
raise ConnectionResetError(*exc.args)
|
| 638 |
+
else:
|
| 639 |
+
raise
|
| 640 |
+
return self._register(ov, sock, finish_sendfile)
|
| 641 |
+
|
| 642 |
+
def accept_pipe(self, pipe):
|
| 643 |
+
self._register_with_iocp(pipe)
|
| 644 |
+
ov = _overlapped.Overlapped(NULL)
|
| 645 |
+
connected = ov.ConnectNamedPipe(pipe.fileno())
|
| 646 |
+
|
| 647 |
+
if connected:
|
| 648 |
+
# ConnectNamePipe() failed with ERROR_PIPE_CONNECTED which means
|
| 649 |
+
# that the pipe is connected. There is no need to wait for the
|
| 650 |
+
# completion of the connection.
|
| 651 |
+
return self._result(pipe)
|
| 652 |
+
|
| 653 |
+
def finish_accept_pipe(trans, key, ov):
|
| 654 |
+
ov.getresult()
|
| 655 |
+
return pipe
|
| 656 |
+
|
| 657 |
+
return self._register(ov, pipe, finish_accept_pipe)
|
| 658 |
+
|
| 659 |
+
async def connect_pipe(self, address):
|
| 660 |
+
delay = CONNECT_PIPE_INIT_DELAY
|
| 661 |
+
while True:
|
| 662 |
+
# Unfortunately there is no way to do an overlapped connect to
|
| 663 |
+
# a pipe. Call CreateFile() in a loop until it doesn't fail with
|
| 664 |
+
# ERROR_PIPE_BUSY.
|
| 665 |
+
try:
|
| 666 |
+
handle = _overlapped.ConnectPipe(address)
|
| 667 |
+
break
|
| 668 |
+
except OSError as exc:
|
| 669 |
+
if exc.winerror != _overlapped.ERROR_PIPE_BUSY:
|
| 670 |
+
raise
|
| 671 |
+
|
| 672 |
+
# ConnectPipe() failed with ERROR_PIPE_BUSY: retry later
|
| 673 |
+
delay = min(delay * 2, CONNECT_PIPE_MAX_DELAY)
|
| 674 |
+
await tasks.sleep(delay)
|
| 675 |
+
|
| 676 |
+
return windows_utils.PipeHandle(handle)
|
| 677 |
+
|
| 678 |
+
def wait_for_handle(self, handle, timeout=None):
|
| 679 |
+
"""Wait for a handle.
|
| 680 |
+
|
| 681 |
+
Return a Future object. The result of the future is True if the wait
|
| 682 |
+
completed, or False if the wait did not complete (on timeout).
|
| 683 |
+
"""
|
| 684 |
+
return self._wait_for_handle(handle, timeout, False)
|
| 685 |
+
|
| 686 |
+
def _wait_cancel(self, event, done_callback):
|
| 687 |
+
fut = self._wait_for_handle(event, None, True)
|
| 688 |
+
# add_done_callback() cannot be used because the wait may only complete
|
| 689 |
+
# in IocpProactor.close(), while the event loop is not running.
|
| 690 |
+
fut._done_callback = done_callback
|
| 691 |
+
return fut
|
| 692 |
+
|
| 693 |
+
def _wait_for_handle(self, handle, timeout, _is_cancel):
|
| 694 |
+
self._check_closed()
|
| 695 |
+
|
| 696 |
+
if timeout is None:
|
| 697 |
+
ms = _winapi.INFINITE
|
| 698 |
+
else:
|
| 699 |
+
# RegisterWaitForSingleObject() has a resolution of 1 millisecond,
|
| 700 |
+
# round away from zero to wait *at least* timeout seconds.
|
| 701 |
+
ms = math.ceil(timeout * 1e3)
|
| 702 |
+
|
| 703 |
+
# We only create ov so we can use ov.address as a key for the cache.
|
| 704 |
+
ov = _overlapped.Overlapped(NULL)
|
| 705 |
+
wait_handle = _overlapped.RegisterWaitWithQueue(
|
| 706 |
+
handle, self._iocp, ov.address, ms)
|
| 707 |
+
if _is_cancel:
|
| 708 |
+
f = _WaitCancelFuture(ov, handle, wait_handle, loop=self._loop)
|
| 709 |
+
else:
|
| 710 |
+
f = _WaitHandleFuture(ov, handle, wait_handle, self,
|
| 711 |
+
loop=self._loop)
|
| 712 |
+
if f._source_traceback:
|
| 713 |
+
del f._source_traceback[-1]
|
| 714 |
+
|
| 715 |
+
def finish_wait_for_handle(trans, key, ov):
|
| 716 |
+
# Note that this second wait means that we should only use
|
| 717 |
+
# this with handles types where a successful wait has no
|
| 718 |
+
# effect. So events or processes are all right, but locks
|
| 719 |
+
# or semaphores are not. Also note if the handle is
|
| 720 |
+
# signalled and then quickly reset, then we may return
|
| 721 |
+
# False even though we have not timed out.
|
| 722 |
+
return f._poll()
|
| 723 |
+
|
| 724 |
+
self._cache[ov.address] = (f, ov, 0, finish_wait_for_handle)
|
| 725 |
+
return f
|
| 726 |
+
|
| 727 |
+
def _register_with_iocp(self, obj):
|
| 728 |
+
# To get notifications of finished ops on this objects sent to the
|
| 729 |
+
# completion port, were must register the handle.
|
| 730 |
+
if obj not in self._registered:
|
| 731 |
+
self._registered.add(obj)
|
| 732 |
+
_overlapped.CreateIoCompletionPort(obj.fileno(), self._iocp, 0, 0)
|
| 733 |
+
# XXX We could also use SetFileCompletionNotificationModes()
|
| 734 |
+
# to avoid sending notifications to completion port of ops
|
| 735 |
+
# that succeed immediately.
|
| 736 |
+
|
| 737 |
+
def _register(self, ov, obj, callback):
|
| 738 |
+
self._check_closed()
|
| 739 |
+
|
| 740 |
+
# Return a future which will be set with the result of the
|
| 741 |
+
# operation when it completes. The future's value is actually
|
| 742 |
+
# the value returned by callback().
|
| 743 |
+
f = _OverlappedFuture(ov, loop=self._loop)
|
| 744 |
+
if f._source_traceback:
|
| 745 |
+
del f._source_traceback[-1]
|
| 746 |
+
if not ov.pending:
|
| 747 |
+
# The operation has completed, so no need to postpone the
|
| 748 |
+
# work. We cannot take this short cut if we need the
|
| 749 |
+
# NumberOfBytes, CompletionKey values returned by
|
| 750 |
+
# PostQueuedCompletionStatus().
|
| 751 |
+
try:
|
| 752 |
+
value = callback(None, None, ov)
|
| 753 |
+
except OSError as e:
|
| 754 |
+
f.set_exception(e)
|
| 755 |
+
else:
|
| 756 |
+
f.set_result(value)
|
| 757 |
+
# Even if GetOverlappedResult() was called, we have to wait for the
|
| 758 |
+
# notification of the completion in GetQueuedCompletionStatus().
|
| 759 |
+
# Register the overlapped operation to keep a reference to the
|
| 760 |
+
# OVERLAPPED object, otherwise the memory is freed and Windows may
|
| 761 |
+
# read uninitialized memory.
|
| 762 |
+
|
| 763 |
+
# Register the overlapped operation for later. Note that
|
| 764 |
+
# we only store obj to prevent it from being garbage
|
| 765 |
+
# collected too early.
|
| 766 |
+
self._cache[ov.address] = (f, ov, obj, callback)
|
| 767 |
+
return f
|
| 768 |
+
|
| 769 |
+
def _unregister(self, ov):
|
| 770 |
+
"""Unregister an overlapped object.
|
| 771 |
+
|
| 772 |
+
Call this method when its future has been cancelled. The event can
|
| 773 |
+
already be signalled (pending in the proactor event queue). It is also
|
| 774 |
+
safe if the event is never signalled (because it was cancelled).
|
| 775 |
+
"""
|
| 776 |
+
self._check_closed()
|
| 777 |
+
self._unregistered.append(ov)
|
| 778 |
+
|
| 779 |
+
def _get_accept_socket(self, family):
|
| 780 |
+
s = socket.socket(family)
|
| 781 |
+
s.settimeout(0)
|
| 782 |
+
return s
|
| 783 |
+
|
| 784 |
+
def _poll(self, timeout=None):
|
| 785 |
+
if timeout is None:
|
| 786 |
+
ms = INFINITE
|
| 787 |
+
elif timeout < 0:
|
| 788 |
+
raise ValueError("negative timeout")
|
| 789 |
+
else:
|
| 790 |
+
# GetQueuedCompletionStatus() has a resolution of 1 millisecond,
|
| 791 |
+
# round away from zero to wait *at least* timeout seconds.
|
| 792 |
+
ms = math.ceil(timeout * 1e3)
|
| 793 |
+
if ms >= INFINITE:
|
| 794 |
+
raise ValueError("timeout too big")
|
| 795 |
+
|
| 796 |
+
while True:
|
| 797 |
+
status = _overlapped.GetQueuedCompletionStatus(self._iocp, ms)
|
| 798 |
+
if status is None:
|
| 799 |
+
break
|
| 800 |
+
ms = 0
|
| 801 |
+
|
| 802 |
+
err, transferred, key, address = status
|
| 803 |
+
try:
|
| 804 |
+
f, ov, obj, callback = self._cache.pop(address)
|
| 805 |
+
except KeyError:
|
| 806 |
+
if self._loop.get_debug():
|
| 807 |
+
self._loop.call_exception_handler({
|
| 808 |
+
'message': ('GetQueuedCompletionStatus() returned an '
|
| 809 |
+
'unexpected event'),
|
| 810 |
+
'status': ('err=%s transferred=%s key=%#x address=%#x'
|
| 811 |
+
% (err, transferred, key, address)),
|
| 812 |
+
})
|
| 813 |
+
|
| 814 |
+
# key is either zero, or it is used to return a pipe
|
| 815 |
+
# handle which should be closed to avoid a leak.
|
| 816 |
+
if key not in (0, _overlapped.INVALID_HANDLE_VALUE):
|
| 817 |
+
_winapi.CloseHandle(key)
|
| 818 |
+
continue
|
| 819 |
+
|
| 820 |
+
if obj in self._stopped_serving:
|
| 821 |
+
f.cancel()
|
| 822 |
+
# Don't call the callback if _register() already read the result or
|
| 823 |
+
# if the overlapped has been cancelled
|
| 824 |
+
elif not f.done():
|
| 825 |
+
try:
|
| 826 |
+
value = callback(transferred, key, ov)
|
| 827 |
+
except OSError as e:
|
| 828 |
+
f.set_exception(e)
|
| 829 |
+
self._results.append(f)
|
| 830 |
+
else:
|
| 831 |
+
f.set_result(value)
|
| 832 |
+
self._results.append(f)
|
| 833 |
+
finally:
|
| 834 |
+
f = None
|
| 835 |
+
|
| 836 |
+
# Remove unregistered futures
|
| 837 |
+
for ov in self._unregistered:
|
| 838 |
+
self._cache.pop(ov.address, None)
|
| 839 |
+
self._unregistered.clear()
|
| 840 |
+
|
| 841 |
+
def _stop_serving(self, obj):
|
| 842 |
+
# obj is a socket or pipe handle. It will be closed in
|
| 843 |
+
# BaseProactorEventLoop._stop_serving() which will make any
|
| 844 |
+
# pending operations fail quickly.
|
| 845 |
+
self._stopped_serving.add(obj)
|
| 846 |
+
|
| 847 |
+
def close(self):
|
| 848 |
+
if self._iocp is None:
|
| 849 |
+
# already closed
|
| 850 |
+
return
|
| 851 |
+
|
| 852 |
+
# Cancel remaining registered operations.
|
| 853 |
+
for address, (fut, ov, obj, callback) in list(self._cache.items()):
|
| 854 |
+
if fut.cancelled():
|
| 855 |
+
# Nothing to do with cancelled futures
|
| 856 |
+
pass
|
| 857 |
+
elif isinstance(fut, _WaitCancelFuture):
|
| 858 |
+
# _WaitCancelFuture must not be cancelled
|
| 859 |
+
pass
|
| 860 |
+
else:
|
| 861 |
+
try:
|
| 862 |
+
fut.cancel()
|
| 863 |
+
except OSError as exc:
|
| 864 |
+
if self._loop is not None:
|
| 865 |
+
context = {
|
| 866 |
+
'message': 'Cancelling a future failed',
|
| 867 |
+
'exception': exc,
|
| 868 |
+
'future': fut,
|
| 869 |
+
}
|
| 870 |
+
if fut._source_traceback:
|
| 871 |
+
context['source_traceback'] = fut._source_traceback
|
| 872 |
+
self._loop.call_exception_handler(context)
|
| 873 |
+
|
| 874 |
+
# Wait until all cancelled overlapped complete: don't exit with running
|
| 875 |
+
# overlapped to prevent a crash. Display progress every second if the
|
| 876 |
+
# loop is still running.
|
| 877 |
+
msg_update = 1.0
|
| 878 |
+
start_time = time.monotonic()
|
| 879 |
+
next_msg = start_time + msg_update
|
| 880 |
+
while self._cache:
|
| 881 |
+
if next_msg <= time.monotonic():
|
| 882 |
+
logger.debug('%r is running after closing for %.1f seconds',
|
| 883 |
+
self, time.monotonic() - start_time)
|
| 884 |
+
next_msg = time.monotonic() + msg_update
|
| 885 |
+
|
| 886 |
+
# handle a few events, or timeout
|
| 887 |
+
self._poll(msg_update)
|
| 888 |
+
|
| 889 |
+
self._results = []
|
| 890 |
+
|
| 891 |
+
_winapi.CloseHandle(self._iocp)
|
| 892 |
+
self._iocp = None
|
| 893 |
+
|
| 894 |
+
def __del__(self):
|
| 895 |
+
self.close()
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
class _WindowsSubprocessTransport(base_subprocess.BaseSubprocessTransport):
|
| 899 |
+
|
| 900 |
+
def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
|
| 901 |
+
self._proc = windows_utils.Popen(
|
| 902 |
+
args, shell=shell, stdin=stdin, stdout=stdout, stderr=stderr,
|
| 903 |
+
bufsize=bufsize, **kwargs)
|
| 904 |
+
|
| 905 |
+
def callback(f):
|
| 906 |
+
returncode = self._proc.poll()
|
| 907 |
+
self._process_exited(returncode)
|
| 908 |
+
|
| 909 |
+
f = self._loop._proactor.wait_for_handle(int(self._proc._handle))
|
| 910 |
+
f.add_done_callback(callback)
|
| 911 |
+
|
| 912 |
+
|
| 913 |
+
SelectorEventLoop = _WindowsSelectorEventLoop
|
| 914 |
+
|
| 915 |
+
|
| 916 |
+
class WindowsSelectorEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
|
| 917 |
+
_loop_factory = SelectorEventLoop
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
class WindowsProactorEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
|
| 921 |
+
_loop_factory = ProactorEventLoop
|
| 922 |
+
|
| 923 |
+
|
| 924 |
+
DefaultEventLoopPolicy = WindowsProactorEventLoopPolicy
|
janus/lib/python3.10/asyncio/windows_utils.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
+
raise ImportError('win32 only')
|
| 7 |
+
|
| 8 |
+
import _winapi
|
| 9 |
+
import itertools
|
| 10 |
+
import msvcrt
|
| 11 |
+
import os
|
| 12 |
+
import subprocess
|
| 13 |
+
import tempfile
|
| 14 |
+
import warnings
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
__all__ = 'pipe', 'Popen', 'PIPE', 'PipeHandle'
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# Constants/globals
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
BUFSIZE = 8192
|
| 24 |
+
PIPE = subprocess.PIPE
|
| 25 |
+
STDOUT = subprocess.STDOUT
|
| 26 |
+
_mmap_counter = itertools.count()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# Replacement for os.pipe() using handles instead of fds
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def pipe(*, duplex=False, overlapped=(True, True), bufsize=BUFSIZE):
|
| 33 |
+
"""Like os.pipe() but with overlapped support and using handles not fds."""
|
| 34 |
+
address = tempfile.mktemp(
|
| 35 |
+
prefix=r'\\.\pipe\python-pipe-{:d}-{:d}-'.format(
|
| 36 |
+
os.getpid(), next(_mmap_counter)))
|
| 37 |
+
|
| 38 |
+
if duplex:
|
| 39 |
+
openmode = _winapi.PIPE_ACCESS_DUPLEX
|
| 40 |
+
access = _winapi.GENERIC_READ | _winapi.GENERIC_WRITE
|
| 41 |
+
obsize, ibsize = bufsize, bufsize
|
| 42 |
+
else:
|
| 43 |
+
openmode = _winapi.PIPE_ACCESS_INBOUND
|
| 44 |
+
access = _winapi.GENERIC_WRITE
|
| 45 |
+
obsize, ibsize = 0, bufsize
|
| 46 |
+
|
| 47 |
+
openmode |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE
|
| 48 |
+
|
| 49 |
+
if overlapped[0]:
|
| 50 |
+
openmode |= _winapi.FILE_FLAG_OVERLAPPED
|
| 51 |
+
|
| 52 |
+
if overlapped[1]:
|
| 53 |
+
flags_and_attribs = _winapi.FILE_FLAG_OVERLAPPED
|
| 54 |
+
else:
|
| 55 |
+
flags_and_attribs = 0
|
| 56 |
+
|
| 57 |
+
h1 = h2 = None
|
| 58 |
+
try:
|
| 59 |
+
h1 = _winapi.CreateNamedPipe(
|
| 60 |
+
address, openmode, _winapi.PIPE_WAIT,
|
| 61 |
+
1, obsize, ibsize, _winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL)
|
| 62 |
+
|
| 63 |
+
h2 = _winapi.CreateFile(
|
| 64 |
+
address, access, 0, _winapi.NULL, _winapi.OPEN_EXISTING,
|
| 65 |
+
flags_and_attribs, _winapi.NULL)
|
| 66 |
+
|
| 67 |
+
ov = _winapi.ConnectNamedPipe(h1, overlapped=True)
|
| 68 |
+
ov.GetOverlappedResult(True)
|
| 69 |
+
return h1, h2
|
| 70 |
+
except:
|
| 71 |
+
if h1 is not None:
|
| 72 |
+
_winapi.CloseHandle(h1)
|
| 73 |
+
if h2 is not None:
|
| 74 |
+
_winapi.CloseHandle(h2)
|
| 75 |
+
raise
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# Wrapper for a pipe handle
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class PipeHandle:
|
| 82 |
+
"""Wrapper for an overlapped pipe handle which is vaguely file-object like.
|
| 83 |
+
|
| 84 |
+
The IOCP event loop can use these instead of socket objects.
|
| 85 |
+
"""
|
| 86 |
+
def __init__(self, handle):
|
| 87 |
+
self._handle = handle
|
| 88 |
+
|
| 89 |
+
def __repr__(self):
|
| 90 |
+
if self._handle is not None:
|
| 91 |
+
handle = f'handle={self._handle!r}'
|
| 92 |
+
else:
|
| 93 |
+
handle = 'closed'
|
| 94 |
+
return f'<{self.__class__.__name__} {handle}>'
|
| 95 |
+
|
| 96 |
+
@property
|
| 97 |
+
def handle(self):
|
| 98 |
+
return self._handle
|
| 99 |
+
|
| 100 |
+
def fileno(self):
|
| 101 |
+
if self._handle is None:
|
| 102 |
+
raise ValueError("I/O operation on closed pipe")
|
| 103 |
+
return self._handle
|
| 104 |
+
|
| 105 |
+
def close(self, *, CloseHandle=_winapi.CloseHandle):
|
| 106 |
+
if self._handle is not None:
|
| 107 |
+
CloseHandle(self._handle)
|
| 108 |
+
self._handle = None
|
| 109 |
+
|
| 110 |
+
def __del__(self, _warn=warnings.warn):
|
| 111 |
+
if self._handle is not None:
|
| 112 |
+
_warn(f"unclosed {self!r}", ResourceWarning, source=self)
|
| 113 |
+
self.close()
|
| 114 |
+
|
| 115 |
+
def __enter__(self):
|
| 116 |
+
return self
|
| 117 |
+
|
| 118 |
+
def __exit__(self, t, v, tb):
|
| 119 |
+
self.close()
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# Replacement for subprocess.Popen using overlapped pipe handles
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class Popen(subprocess.Popen):
|
| 126 |
+
"""Replacement for subprocess.Popen using overlapped pipe handles.
|
| 127 |
+
|
| 128 |
+
The stdin, stdout, stderr are None or instances of PipeHandle.
|
| 129 |
+
"""
|
| 130 |
+
def __init__(self, args, stdin=None, stdout=None, stderr=None, **kwds):
|
| 131 |
+
assert not kwds.get('universal_newlines')
|
| 132 |
+
assert kwds.get('bufsize', 0) == 0
|
| 133 |
+
stdin_rfd = stdout_wfd = stderr_wfd = None
|
| 134 |
+
stdin_wh = stdout_rh = stderr_rh = None
|
| 135 |
+
if stdin == PIPE:
|
| 136 |
+
stdin_rh, stdin_wh = pipe(overlapped=(False, True), duplex=True)
|
| 137 |
+
stdin_rfd = msvcrt.open_osfhandle(stdin_rh, os.O_RDONLY)
|
| 138 |
+
else:
|
| 139 |
+
stdin_rfd = stdin
|
| 140 |
+
if stdout == PIPE:
|
| 141 |
+
stdout_rh, stdout_wh = pipe(overlapped=(True, False))
|
| 142 |
+
stdout_wfd = msvcrt.open_osfhandle(stdout_wh, 0)
|
| 143 |
+
else:
|
| 144 |
+
stdout_wfd = stdout
|
| 145 |
+
if stderr == PIPE:
|
| 146 |
+
stderr_rh, stderr_wh = pipe(overlapped=(True, False))
|
| 147 |
+
stderr_wfd = msvcrt.open_osfhandle(stderr_wh, 0)
|
| 148 |
+
elif stderr == STDOUT:
|
| 149 |
+
stderr_wfd = stdout_wfd
|
| 150 |
+
else:
|
| 151 |
+
stderr_wfd = stderr
|
| 152 |
+
try:
|
| 153 |
+
super().__init__(args, stdin=stdin_rfd, stdout=stdout_wfd,
|
| 154 |
+
stderr=stderr_wfd, **kwds)
|
| 155 |
+
except:
|
| 156 |
+
for h in (stdin_wh, stdout_rh, stderr_rh):
|
| 157 |
+
if h is not None:
|
| 158 |
+
_winapi.CloseHandle(h)
|
| 159 |
+
raise
|
| 160 |
+
else:
|
| 161 |
+
if stdin_wh is not None:
|
| 162 |
+
self.stdin = PipeHandle(stdin_wh)
|
| 163 |
+
if stdout_rh is not None:
|
| 164 |
+
self.stdout = PipeHandle(stdout_rh)
|
| 165 |
+
if stderr_rh is not None:
|
| 166 |
+
self.stderr = PipeHandle(stderr_rh)
|
| 167 |
+
finally:
|
| 168 |
+
if stdin == PIPE:
|
| 169 |
+
os.close(stdin_rfd)
|
| 170 |
+
if stdout == PIPE:
|
| 171 |
+
os.close(stdout_wfd)
|
| 172 |
+
if stderr == PIPE:
|
| 173 |
+
os.close(stderr_wfd)
|
janus/lib/python3.10/site-packages/idna-3.10.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
janus/lib/python3.10/site-packages/idna-3.10.dist-info/LICENSE.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
BSD 3-Clause License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2013-2024, Kim Davies and contributors.
|
| 4 |
+
All rights reserved.
|
| 5 |
+
|
| 6 |
+
Redistribution and use in source and binary forms, with or without
|
| 7 |
+
modification, are permitted provided that the following conditions are
|
| 8 |
+
met:
|
| 9 |
+
|
| 10 |
+
1. Redistributions of source code must retain the above copyright
|
| 11 |
+
notice, this list of conditions and the following disclaimer.
|
| 12 |
+
|
| 13 |
+
2. Redistributions in binary form must reproduce the above copyright
|
| 14 |
+
notice, this list of conditions and the following disclaimer in the
|
| 15 |
+
documentation and/or other materials provided with the distribution.
|
| 16 |
+
|
| 17 |
+
3. Neither the name of the copyright holder nor the names of its
|
| 18 |
+
contributors may be used to endorse or promote products derived from
|
| 19 |
+
this software without specific prior written permission.
|
| 20 |
+
|
| 21 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 22 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 23 |
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
| 24 |
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
| 25 |
+
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
| 26 |
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
| 27 |
+
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
| 28 |
+
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
| 29 |
+
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
| 30 |
+
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
| 31 |
+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUC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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: idna
|
| 3 |
+
Version: 3.10
|
| 4 |
+
Summary: Internationalized Domain Names in Applications (IDNA)
|
| 5 |
+
Author-email: Kim Davies <kim+pypi@gumleaf.org>
|
| 6 |
+
Requires-Python: >=3.6
|
| 7 |
+
Description-Content-Type: text/x-rst
|
| 8 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 9 |
+
Classifier: Intended Audience :: Developers
|
| 10 |
+
Classifier: Intended Audience :: System Administrators
|
| 11 |
+
Classifier: License :: OSI Approved :: BSD License
|
| 12 |
+
Classifier: Operating System :: OS Independent
|
| 13 |
+
Classifier: Programming Language :: Python
|
| 14 |
+
Classifier: Programming Language :: Python :: 3
|
| 15 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 16 |
+
Classifier: Programming Language :: Python :: 3.6
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.7
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 24 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 25 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 26 |
+
Classifier: Topic :: Internet :: Name Service (DNS)
|
| 27 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
| 28 |
+
Classifier: Topic :: Utilities
|
| 29 |
+
Requires-Dist: ruff >= 0.6.2 ; extra == "all"
|
| 30 |
+
Requires-Dist: mypy >= 1.11.2 ; extra == "all"
|
| 31 |
+
Requires-Dist: pytest >= 8.3.2 ; extra == "all"
|
| 32 |
+
Requires-Dist: flake8 >= 7.1.1 ; extra == "all"
|
| 33 |
+
Project-URL: Changelog, https://github.com/kjd/idna/blob/master/HISTORY.rst
|
| 34 |
+
Project-URL: Issue tracker, https://github.com/kjd/idna/issues
|
| 35 |
+
Project-URL: Source, https://github.com/kjd/idna
|
| 36 |
+
Provides-Extra: all
|
| 37 |
+
|
| 38 |
+
Internationalized Domain Names in Applications (IDNA)
|
| 39 |
+
=====================================================
|
| 40 |
+
|
| 41 |
+
Support for the Internationalized Domain Names in
|
| 42 |
+
Applications (IDNA) protocol as specified in `RFC 5891
|
| 43 |
+
<https://tools.ietf.org/html/rfc5891>`_. This is the latest version of
|
| 44 |
+
the protocol and is sometimes referred to as “IDNA 2008”.
|
| 45 |
+
|
| 46 |
+
This library also provides support for Unicode Technical
|
| 47 |
+
Standard 46, `Unicode IDNA Compatibility Processing
|
| 48 |
+
<https://unicode.org/reports/tr46/>`_.
|
| 49 |
+
|
| 50 |
+
This acts as a suitable replacement for the “encodings.idna”
|
| 51 |
+
module that comes with the Python standard library, but which
|
| 52 |
+
only supports the older superseded IDNA specification (`RFC 3490
|
| 53 |
+
<https://tools.ietf.org/html/rfc3490>`_).
|
| 54 |
+
|
| 55 |
+
Basic functions are simply executed:
|
| 56 |
+
|
| 57 |
+
.. code-block:: pycon
|
| 58 |
+
|
| 59 |
+
>>> import idna
|
| 60 |
+
>>> idna.encode('ドメイン.テスト')
|
| 61 |
+
b'xn--eckwd4c7c.xn--zckzah'
|
| 62 |
+
>>> print(idna.decode('xn--eckwd4c7c.xn--zckzah'))
|
| 63 |
+
ドメイン.テスト
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
Installation
|
| 67 |
+
------------
|
| 68 |
+
|
| 69 |
+
This package is available for installation from PyPI:
|
| 70 |
+
|
| 71 |
+
.. code-block:: bash
|
| 72 |
+
|
| 73 |
+
$ python3 -m pip install idna
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
Usage
|
| 77 |
+
-----
|
| 78 |
+
|
| 79 |
+
For typical usage, the ``encode`` and ``decode`` functions will take a
|
| 80 |
+
domain name argument and perform a conversion to A-labels or U-labels
|
| 81 |
+
respectively.
|
| 82 |
+
|
| 83 |
+
.. code-block:: pycon
|
| 84 |
+
|
| 85 |
+
>>> import idna
|
| 86 |
+
>>> idna.encode('ドメイン.テスト')
|
| 87 |
+
b'xn--eckwd4c7c.xn--zckzah'
|
| 88 |
+
>>> print(idna.decode('xn--eckwd4c7c.xn--zckzah'))
|
| 89 |
+
ドメイン.テスト
|
| 90 |
+
|
| 91 |
+
You may use the codec encoding and decoding methods using the
|
| 92 |
+
``idna.codec`` module:
|
| 93 |
+
|
| 94 |
+
.. code-block:: pycon
|
| 95 |
+
|
| 96 |
+
>>> import idna.codec
|
| 97 |
+
>>> print('домен.испытание'.encode('idna2008'))
|
| 98 |
+
b'xn--d1acufc.xn--80akhbyknj4f'
|
| 99 |
+
>>> print(b'xn--d1acufc.xn--80akhbyknj4f'.decode('idna2008'))
|
| 100 |
+
домен.испытание
|
| 101 |
+
|
| 102 |
+
Conversions can be applied at a per-label basis using the ``ulabel`` or
|
| 103 |
+
``alabel`` functions if necessary:
|
| 104 |
+
|
| 105 |
+
.. code-block:: pycon
|
| 106 |
+
|
| 107 |
+
>>> idna.alabel('测试')
|
| 108 |
+
b'xn--0zwm56d'
|
| 109 |
+
|
| 110 |
+
Compatibility Mapping (UTS #46)
|
| 111 |
+
+++++++++++++++++++++++++++++++
|
| 112 |
+
|
| 113 |
+
As described in `RFC 5895 <https://tools.ietf.org/html/rfc5895>`_, the
|
| 114 |
+
IDNA specification does not normalize input from different potential
|
| 115 |
+
ways a user may input a domain name. This functionality, known as
|
| 116 |
+
a “mapping”, is considered by the specification to be a local
|
| 117 |
+
user-interface issue distinct from IDNA conversion functionality.
|
| 118 |
+
|
| 119 |
+
This library provides one such mapping that was developed by the
|
| 120 |
+
Unicode Consortium. Known as `Unicode IDNA Compatibility Processing
|
| 121 |
+
<https://unicode.org/reports/tr46/>`_, it provides for both a regular
|
| 122 |
+
mapping for typical applications, as well as a transitional mapping to
|
| 123 |
+
help migrate from older IDNA 2003 applications. Strings are
|
| 124 |
+
preprocessed according to Section 4.4 “Preprocessing for IDNA2008”
|
| 125 |
+
prior to the IDNA operations.
|
| 126 |
+
|
| 127 |
+
For example, “Königsgäßchen” is not a permissible label as *LATIN
|
| 128 |
+
CAPITAL LETTER K* is not allowed (nor are capital letters in general).
|
| 129 |
+
UTS 46 will convert this into lower case prior to applying the IDNA
|
| 130 |
+
conversion.
|
| 131 |
+
|
| 132 |
+
.. code-block:: pycon
|
| 133 |
+
|
| 134 |
+
>>> import idna
|
| 135 |
+
>>> idna.encode('Königsgäßchen')
|
| 136 |
+
...
|
| 137 |
+
idna.core.InvalidCodepoint: Codepoint U+004B at position 1 of 'Königsgäßchen' not allowed
|
| 138 |
+
>>> idna.encode('Königsgäßchen', uts46=True)
|
| 139 |
+
b'xn--knigsgchen-b4a3dun'
|
| 140 |
+
>>> print(idna.decode('xn--knigsgchen-b4a3dun'))
|
| 141 |
+
königsgäßchen
|
| 142 |
+
|
| 143 |
+
Transitional processing provides conversions to help transition from
|
| 144 |
+
the older 2003 standard to the current standard. For example, in the
|
| 145 |
+
original IDNA specification, the *LATIN SMALL LETTER SHARP S* (ß) was
|
| 146 |
+
converted into two *LATIN SMALL LETTER S* (ss), whereas in the current
|
| 147 |
+
IDNA specification this conversion is not performed.
|
| 148 |
+
|
| 149 |
+
.. code-block:: pycon
|
| 150 |
+
|
| 151 |
+
>>> idna.encode('Königsgäßchen', uts46=True, transitional=True)
|
| 152 |
+
'xn--knigsgsschen-lcb0w'
|
| 153 |
+
|
| 154 |
+
Implementers should use transitional processing with caution, only in
|
| 155 |
+
rare cases where conversion from legacy labels to current labels must be
|
| 156 |
+
performed (i.e. IDNA implementations that pre-date 2008). For typical
|
| 157 |
+
applications that just need to convert labels, transitional processing
|
| 158 |
+
is unlikely to be beneficial and could produce unexpected incompatible
|
| 159 |
+
results.
|
| 160 |
+
|
| 161 |
+
``encodings.idna`` Compatibility
|
| 162 |
+
++++++++++++++++++++++++++++++++
|
| 163 |
+
|
| 164 |
+
Function calls from the Python built-in ``encodings.idna`` module are
|
| 165 |
+
mapped to their IDNA 2008 equivalents using the ``idna.compat`` module.
|
| 166 |
+
Simply substitute the ``import`` clause in your code to refer to the new
|
| 167 |
+
module name.
|
| 168 |
+
|
| 169 |
+
Exceptions
|
| 170 |
+
----------
|
| 171 |
+
|
| 172 |
+
All errors raised during the conversion following the specification
|
| 173 |
+
should raise an exception derived from the ``idna.IDNAError`` base
|
| 174 |
+
class.
|
| 175 |
+
|
| 176 |
+
More specific exceptions that may be generated as ``idna.IDNABidiError``
|
| 177 |
+
when the error reflects an illegal combination of left-to-right and
|
| 178 |
+
right-to-left characters in a label; ``idna.InvalidCodepoint`` when
|
| 179 |
+
a specific codepoint is an illegal character in an IDN label (i.e.
|
| 180 |
+
INVALID); and ``idna.InvalidCodepointContext`` when the codepoint is
|
| 181 |
+
illegal based on its positional context (i.e. it is CONTEXTO or CONTEXTJ
|
| 182 |
+
but the contextual requirements are not satisfied.)
|
| 183 |
+
|
| 184 |
+
Building and Diagnostics
|
| 185 |
+
------------------------
|
| 186 |
+
|
| 187 |
+
The IDNA and UTS 46 functionality relies upon pre-calculated lookup
|
| 188 |
+
tables for performance. These tables are derived from computing against
|
| 189 |
+
eligibility criteria in the respective standards. These tables are
|
| 190 |
+
computed using the command-line script ``tools/idna-data``.
|
| 191 |
+
|
| 192 |
+
This tool will fetch relevant codepoint data from the Unicode repository
|
| 193 |
+
and perform the required calculations to identify eligibility. There are
|
| 194 |
+
three main modes:
|
| 195 |
+
|
| 196 |
+
* ``idna-data make-libdata``. Generates ``idnadata.py`` and
|
| 197 |
+
``uts46data.py``, the pre-calculated lookup tables used for IDNA and
|
| 198 |
+
UTS 46 conversions. Implementers who wish to track this library against
|
| 199 |
+
a different Unicode version may use this tool to manually generate a
|
| 200 |
+
different version of the ``idnadata.py`` and ``uts46data.py`` files.
|
| 201 |
+
|
| 202 |
+
* ``idna-data make-table``. Generate a table of the IDNA disposition
|
| 203 |
+
(e.g. PVALID, CONTEXTJ, CONTEXTO) in the format found in Appendix
|
| 204 |
+
B.1 of RFC 5892 and the pre-computed tables published by `IANA
|
| 205 |
+
<https://www.iana.org/>`_.
|
| 206 |
+
|
| 207 |
+
* ``idna-data U+0061``. Prints debugging output on the various
|
| 208 |
+
properties associated with an individual Unicode codepoint (in this
|
| 209 |
+
case, U+0061), that are used to assess the IDNA and UTS 46 status of a
|
| 210 |
+
codepoint. This is helpful in debugging or analysis.
|
| 211 |
+
|
| 212 |
+
The tool accepts a number of arguments, described using ``idna-data
|
| 213 |
+
-h``. Most notably, the ``--version`` argument allows the specification
|
| 214 |
+
of the version of Unicode to be used in computing the table data. For
|
| 215 |
+
example, ``idna-data --version 9.0.0 make-libdata`` will generate
|
| 216 |
+
library data against Unicode 9.0.0.
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
Additional Notes
|
| 220 |
+
----------------
|
| 221 |
+
|
| 222 |
+
* **Packages**. The latest tagged release version is published in the
|
| 223 |
+
`Python Package Index <https://pypi.org/project/idna/>`_.
|
| 224 |
+
|
| 225 |
+
* **Version support**. This library supports Python 3.6 and higher.
|
| 226 |
+
As this library serves as a low-level toolkit for a variety of
|
| 227 |
+
applications, many of which strive for broad compatibility with older
|
| 228 |
+
Python versions, there is no rush to remove older interpreter support.
|
| 229 |
+
Removing support for older versions should be well justified in that the
|
| 230 |
+
maintenance burden has become too high.
|
| 231 |
+
|
| 232 |
+
* **Python 2**. Python 2 is supported by version 2.x of this library.
|
| 233 |
+
Use "idna<3" in your requirements file if you need this library for
|
| 234 |
+
a Python 2 application. Be advised that these versions are no longer
|
| 235 |
+
actively developed.
|
| 236 |
+
|
| 237 |
+
* **Testing**. The library has a test suite based on each rule of the
|
| 238 |
+
IDNA specification, as well as tests that are provided as part of the
|
| 239 |
+
Unicode Technical Standard 46, `Unicode IDNA Compatibility Processing
|
| 240 |
+
<https://unicode.org/reports/tr46/>`_.
|
| 241 |
+
|
| 242 |
+
* **Emoji**. It is an occasional request to support emoji domains in
|
| 243 |
+
this library. Encoding of symbols like emoji is expressly prohibited by
|
| 244 |
+
the technical standard IDNA 2008 and emoji domains are broadly phased
|
| 245 |
+
out across the domain industry due to associated security risks. For
|
| 246 |
+
now, applications that need to support these non-compliant labels
|
| 247 |
+
may wish to consider trying the encode/decode operation in this library
|
| 248 |
+
first, and then falling back to using `encodings.idna`. See `the Github
|
| 249 |
+
project <https://github.com/kjd/idna/issues/18>`_ for more discussion.
|
| 250 |
+
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.59 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/_identifier.cpython-310.pyc
ADDED
|
Binary file (2.06 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/async_utils.cpython-310.pyc
ADDED
|
Binary file (3.44 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/compiler.cpython-310.pyc
ADDED
|
Binary file (55.2 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/constants.cpython-310.pyc
ADDED
|
Binary file (1.52 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/debug.cpython-310.pyc
ADDED
|
Binary file (3.98 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/environment.cpython-310.pyc
ADDED
|
Binary file (53.4 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/ext.cpython-310.pyc
ADDED
|
Binary file (25.9 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/filters.cpython-310.pyc
ADDED
|
Binary file (52.2 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/idtracking.cpython-310.pyc
ADDED
|
Binary file (11.1 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/lexer.cpython-310.pyc
ADDED
|
Binary file (20.4 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/loaders.cpython-310.pyc
ADDED
|
Binary file (21.2 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/meta.cpython-310.pyc
ADDED
|
Binary file (3.8 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/nativetypes.cpython-310.pyc
ADDED
|
Binary file (5 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/nodes.cpython-310.pyc
ADDED
|
Binary file (40.3 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/optimizer.cpython-310.pyc
ADDED
|
Binary file (1.94 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/parser.cpython-310.pyc
ADDED
|
Binary file (28.1 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/runtime.cpython-310.pyc
ADDED
|
Binary file (32.3 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/sandbox.cpython-310.pyc
ADDED
|
Binary file (12.2 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/tests.cpython-310.pyc
ADDED
|
Binary file (6.68 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (24.8 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/__pycache__/visitor.cpython-310.pyc
ADDED
|
Binary file (3.96 kB). View file
|
|
|
janus/lib/python3.10/site-packages/jinja2/async_utils.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import typing as t
|
| 3 |
+
from functools import WRAPPER_ASSIGNMENTS
|
| 4 |
+
from functools import wraps
|
| 5 |
+
|
| 6 |
+
from .utils import _PassArg
|
| 7 |
+
from .utils import pass_eval_context
|
| 8 |
+
|
| 9 |
+
if t.TYPE_CHECKING:
|
| 10 |
+
import typing_extensions as te
|
| 11 |
+
|
| 12 |
+
V = t.TypeVar("V")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def async_variant(normal_func): # type: ignore
|
| 16 |
+
def decorator(async_func): # type: ignore
|
| 17 |
+
pass_arg = _PassArg.from_obj(normal_func)
|
| 18 |
+
need_eval_context = pass_arg is None
|
| 19 |
+
|
| 20 |
+
if pass_arg is _PassArg.environment:
|
| 21 |
+
|
| 22 |
+
def is_async(args: t.Any) -> bool:
|
| 23 |
+
return t.cast(bool, args[0].is_async)
|
| 24 |
+
|
| 25 |
+
else:
|
| 26 |
+
|
| 27 |
+
def is_async(args: t.Any) -> bool:
|
| 28 |
+
return t.cast(bool, args[0].environment.is_async)
|
| 29 |
+
|
| 30 |
+
# Take the doc and annotations from the sync function, but the
|
| 31 |
+
# name from the async function. Pallets-Sphinx-Themes
|
| 32 |
+
# build_function_directive expects __wrapped__ to point to the
|
| 33 |
+
# sync function.
|
| 34 |
+
async_func_attrs = ("__module__", "__name__", "__qualname__")
|
| 35 |
+
normal_func_attrs = tuple(set(WRAPPER_ASSIGNMENTS).difference(async_func_attrs))
|
| 36 |
+
|
| 37 |
+
@wraps(normal_func, assigned=normal_func_attrs)
|
| 38 |
+
@wraps(async_func, assigned=async_func_attrs, updated=())
|
| 39 |
+
def wrapper(*args, **kwargs): # type: ignore
|
| 40 |
+
b = is_async(args)
|
| 41 |
+
|
| 42 |
+
if need_eval_context:
|
| 43 |
+
args = args[1:]
|
| 44 |
+
|
| 45 |
+
if b:
|
| 46 |
+
return async_func(*args, **kwargs)
|
| 47 |
+
|
| 48 |
+
return normal_func(*args, **kwargs)
|
| 49 |
+
|
| 50 |
+
if need_eval_context:
|
| 51 |
+
wrapper = pass_eval_context(wrapper)
|
| 52 |
+
|
| 53 |
+
wrapper.jinja_async_variant = True # type: ignore[attr-defined]
|
| 54 |
+
return wrapper
|
| 55 |
+
|
| 56 |
+
return decorator
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
_common_primitives = {int, float, bool, str, list, dict, tuple, type(None)}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
async def auto_await(value: t.Union[t.Awaitable["V"], "V"]) -> "V":
|
| 63 |
+
# Avoid a costly call to isawaitable
|
| 64 |
+
if type(value) in _common_primitives:
|
| 65 |
+
return t.cast("V", value)
|
| 66 |
+
|
| 67 |
+
if inspect.isawaitable(value):
|
| 68 |
+
return await t.cast("t.Awaitable[V]", value)
|
| 69 |
+
|
| 70 |
+
return value
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class _IteratorToAsyncIterator(t.Generic[V]):
|
| 74 |
+
def __init__(self, iterator: "t.Iterator[V]"):
|
| 75 |
+
self._iterator = iterator
|
| 76 |
+
|
| 77 |
+
def __aiter__(self) -> "te.Self":
|
| 78 |
+
return self
|
| 79 |
+
|
| 80 |
+
async def __anext__(self) -> V:
|
| 81 |
+
try:
|
| 82 |
+
return next(self._iterator)
|
| 83 |
+
except StopIteration as e:
|
| 84 |
+
raise StopAsyncIteration(e.value) from e
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def auto_aiter(
|
| 88 |
+
iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
| 89 |
+
) -> "t.AsyncIterator[V]":
|
| 90 |
+
if hasattr(iterable, "__aiter__"):
|
| 91 |
+
return iterable.__aiter__()
|
| 92 |
+
else:
|
| 93 |
+
return _IteratorToAsyncIterator(iter(iterable))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
async def auto_to_list(
|
| 97 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
| 98 |
+
) -> t.List["V"]:
|
| 99 |
+
return [x async for x in auto_aiter(value)]
|
janus/lib/python3.10/site-packages/jinja2/filters.py
ADDED
|
@@ -0,0 +1,1878 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|`` operator."""
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
import random
|
| 5 |
+
import re
|
| 6 |
+
import typing
|
| 7 |
+
import typing as t
|
| 8 |
+
from collections import abc
|
| 9 |
+
from itertools import chain
|
| 10 |
+
from itertools import groupby
|
| 11 |
+
|
| 12 |
+
from markupsafe import escape
|
| 13 |
+
from markupsafe import Markup
|
| 14 |
+
from markupsafe import soft_str
|
| 15 |
+
|
| 16 |
+
from .async_utils import async_variant
|
| 17 |
+
from .async_utils import auto_aiter
|
| 18 |
+
from .async_utils import auto_await
|
| 19 |
+
from .async_utils import auto_to_list
|
| 20 |
+
from .exceptions import FilterArgumentError
|
| 21 |
+
from .runtime import Undefined
|
| 22 |
+
from .utils import htmlsafe_json_dumps
|
| 23 |
+
from .utils import pass_context
|
| 24 |
+
from .utils import pass_environment
|
| 25 |
+
from .utils import pass_eval_context
|
| 26 |
+
from .utils import pformat
|
| 27 |
+
from .utils import url_quote
|
| 28 |
+
from .utils import urlize
|
| 29 |
+
|
| 30 |
+
if t.TYPE_CHECKING:
|
| 31 |
+
import typing_extensions as te
|
| 32 |
+
|
| 33 |
+
from .environment import Environment
|
| 34 |
+
from .nodes import EvalContext
|
| 35 |
+
from .runtime import Context
|
| 36 |
+
from .sandbox import SandboxedEnvironment # noqa: F401
|
| 37 |
+
|
| 38 |
+
class HasHTML(te.Protocol):
|
| 39 |
+
def __html__(self) -> str:
|
| 40 |
+
pass
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
F = t.TypeVar("F", bound=t.Callable[..., t.Any])
|
| 44 |
+
K = t.TypeVar("K")
|
| 45 |
+
V = t.TypeVar("V")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def ignore_case(value: V) -> V:
|
| 49 |
+
"""For use as a postprocessor for :func:`make_attrgetter`. Converts strings
|
| 50 |
+
to lowercase and returns other types as-is."""
|
| 51 |
+
if isinstance(value, str):
|
| 52 |
+
return t.cast(V, value.lower())
|
| 53 |
+
|
| 54 |
+
return value
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def make_attrgetter(
|
| 58 |
+
environment: "Environment",
|
| 59 |
+
attribute: t.Optional[t.Union[str, int]],
|
| 60 |
+
postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None,
|
| 61 |
+
default: t.Optional[t.Any] = None,
|
| 62 |
+
) -> t.Callable[[t.Any], t.Any]:
|
| 63 |
+
"""Returns a callable that looks up the given attribute from a
|
| 64 |
+
passed object with the rules of the environment. Dots are allowed
|
| 65 |
+
to access attributes of attributes. Integer parts in paths are
|
| 66 |
+
looked up as integers.
|
| 67 |
+
"""
|
| 68 |
+
parts = _prepare_attribute_parts(attribute)
|
| 69 |
+
|
| 70 |
+
def attrgetter(item: t.Any) -> t.Any:
|
| 71 |
+
for part in parts:
|
| 72 |
+
item = environment.getitem(item, part)
|
| 73 |
+
|
| 74 |
+
if default is not None and isinstance(item, Undefined):
|
| 75 |
+
item = default
|
| 76 |
+
|
| 77 |
+
if postprocess is not None:
|
| 78 |
+
item = postprocess(item)
|
| 79 |
+
|
| 80 |
+
return item
|
| 81 |
+
|
| 82 |
+
return attrgetter
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def make_multi_attrgetter(
|
| 86 |
+
environment: "Environment",
|
| 87 |
+
attribute: t.Optional[t.Union[str, int]],
|
| 88 |
+
postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None,
|
| 89 |
+
) -> t.Callable[[t.Any], t.List[t.Any]]:
|
| 90 |
+
"""Returns a callable that looks up the given comma separated
|
| 91 |
+
attributes from a passed object with the rules of the environment.
|
| 92 |
+
Dots are allowed to access attributes of each attribute. Integer
|
| 93 |
+
parts in paths are looked up as integers.
|
| 94 |
+
|
| 95 |
+
The value returned by the returned callable is a list of extracted
|
| 96 |
+
attribute values.
|
| 97 |
+
|
| 98 |
+
Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.
|
| 99 |
+
"""
|
| 100 |
+
if isinstance(attribute, str):
|
| 101 |
+
split: t.Sequence[t.Union[str, int, None]] = attribute.split(",")
|
| 102 |
+
else:
|
| 103 |
+
split = [attribute]
|
| 104 |
+
|
| 105 |
+
parts = [_prepare_attribute_parts(item) for item in split]
|
| 106 |
+
|
| 107 |
+
def attrgetter(item: t.Any) -> t.List[t.Any]:
|
| 108 |
+
items = [None] * len(parts)
|
| 109 |
+
|
| 110 |
+
for i, attribute_part in enumerate(parts):
|
| 111 |
+
item_i = item
|
| 112 |
+
|
| 113 |
+
for part in attribute_part:
|
| 114 |
+
item_i = environment.getitem(item_i, part)
|
| 115 |
+
|
| 116 |
+
if postprocess is not None:
|
| 117 |
+
item_i = postprocess(item_i)
|
| 118 |
+
|
| 119 |
+
items[i] = item_i
|
| 120 |
+
|
| 121 |
+
return items
|
| 122 |
+
|
| 123 |
+
return attrgetter
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _prepare_attribute_parts(
|
| 127 |
+
attr: t.Optional[t.Union[str, int]],
|
| 128 |
+
) -> t.List[t.Union[str, int]]:
|
| 129 |
+
if attr is None:
|
| 130 |
+
return []
|
| 131 |
+
|
| 132 |
+
if isinstance(attr, str):
|
| 133 |
+
return [int(x) if x.isdigit() else x for x in attr.split(".")]
|
| 134 |
+
|
| 135 |
+
return [attr]
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def do_forceescape(value: "t.Union[str, HasHTML]") -> Markup:
|
| 139 |
+
"""Enforce HTML escaping. This will probably double escape variables."""
|
| 140 |
+
if hasattr(value, "__html__"):
|
| 141 |
+
value = t.cast("HasHTML", value).__html__()
|
| 142 |
+
|
| 143 |
+
return escape(str(value))
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def do_urlencode(
|
| 147 |
+
value: t.Union[str, t.Mapping[str, t.Any], t.Iterable[t.Tuple[str, t.Any]]],
|
| 148 |
+
) -> str:
|
| 149 |
+
"""Quote data for use in a URL path or query using UTF-8.
|
| 150 |
+
|
| 151 |
+
Basic wrapper around :func:`urllib.parse.quote` when given a
|
| 152 |
+
string, or :func:`urllib.parse.urlencode` for a dict or iterable.
|
| 153 |
+
|
| 154 |
+
:param value: Data to quote. A string will be quoted directly. A
|
| 155 |
+
dict or iterable of ``(key, value)`` pairs will be joined as a
|
| 156 |
+
query string.
|
| 157 |
+
|
| 158 |
+
When given a string, "/" is not quoted. HTTP servers treat "/" and
|
| 159 |
+
"%2F" equivalently in paths. If you need quoted slashes, use the
|
| 160 |
+
``|replace("/", "%2F")`` filter.
|
| 161 |
+
|
| 162 |
+
.. versionadded:: 2.7
|
| 163 |
+
"""
|
| 164 |
+
if isinstance(value, str) or not isinstance(value, abc.Iterable):
|
| 165 |
+
return url_quote(value)
|
| 166 |
+
|
| 167 |
+
if isinstance(value, dict):
|
| 168 |
+
items: t.Iterable[t.Tuple[str, t.Any]] = value.items()
|
| 169 |
+
else:
|
| 170 |
+
items = value # type: ignore
|
| 171 |
+
|
| 172 |
+
return "&".join(
|
| 173 |
+
f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
@pass_eval_context
|
| 178 |
+
def do_replace(
|
| 179 |
+
eval_ctx: "EvalContext", s: str, old: str, new: str, count: t.Optional[int] = None
|
| 180 |
+
) -> str:
|
| 181 |
+
"""Return a copy of the value with all occurrences of a substring
|
| 182 |
+
replaced with a new one. The first argument is the substring
|
| 183 |
+
that should be replaced, the second is the replacement string.
|
| 184 |
+
If the optional third argument ``count`` is given, only the first
|
| 185 |
+
``count`` occurrences are replaced:
|
| 186 |
+
|
| 187 |
+
.. sourcecode:: jinja
|
| 188 |
+
|
| 189 |
+
{{ "Hello World"|replace("Hello", "Goodbye") }}
|
| 190 |
+
-> Goodbye World
|
| 191 |
+
|
| 192 |
+
{{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
|
| 193 |
+
-> d'oh, d'oh, aaargh
|
| 194 |
+
"""
|
| 195 |
+
if count is None:
|
| 196 |
+
count = -1
|
| 197 |
+
|
| 198 |
+
if not eval_ctx.autoescape:
|
| 199 |
+
return str(s).replace(str(old), str(new), count)
|
| 200 |
+
|
| 201 |
+
if (
|
| 202 |
+
hasattr(old, "__html__")
|
| 203 |
+
or hasattr(new, "__html__")
|
| 204 |
+
and not hasattr(s, "__html__")
|
| 205 |
+
):
|
| 206 |
+
s = escape(s)
|
| 207 |
+
else:
|
| 208 |
+
s = soft_str(s)
|
| 209 |
+
|
| 210 |
+
return s.replace(soft_str(old), soft_str(new), count)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def do_upper(s: str) -> str:
|
| 214 |
+
"""Convert a value to uppercase."""
|
| 215 |
+
return soft_str(s).upper()
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def do_lower(s: str) -> str:
|
| 219 |
+
"""Convert a value to lowercase."""
|
| 220 |
+
return soft_str(s).lower()
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def do_items(value: t.Union[t.Mapping[K, V], Undefined]) -> t.Iterator[t.Tuple[K, V]]:
|
| 224 |
+
"""Return an iterator over the ``(key, value)`` items of a mapping.
|
| 225 |
+
|
| 226 |
+
``x|items`` is the same as ``x.items()``, except if ``x`` is
|
| 227 |
+
undefined an empty iterator is returned.
|
| 228 |
+
|
| 229 |
+
This filter is useful if you expect the template to be rendered with
|
| 230 |
+
an implementation of Jinja in another programming language that does
|
| 231 |
+
not have a ``.items()`` method on its mapping type.
|
| 232 |
+
|
| 233 |
+
.. code-block:: html+jinja
|
| 234 |
+
|
| 235 |
+
<dl>
|
| 236 |
+
{% for key, value in my_dict|items %}
|
| 237 |
+
<dt>{{ key }}
|
| 238 |
+
<dd>{{ value }}
|
| 239 |
+
{% endfor %}
|
| 240 |
+
</dl>
|
| 241 |
+
|
| 242 |
+
.. versionadded:: 3.1
|
| 243 |
+
"""
|
| 244 |
+
if isinstance(value, Undefined):
|
| 245 |
+
return
|
| 246 |
+
|
| 247 |
+
if not isinstance(value, abc.Mapping):
|
| 248 |
+
raise TypeError("Can only get item pairs from a mapping.")
|
| 249 |
+
|
| 250 |
+
yield from value.items()
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
# Check for characters that would move the parser state from key to value.
|
| 254 |
+
# https://html.spec.whatwg.org/#attribute-name-state
|
| 255 |
+
_attr_key_re = re.compile(r"[\s/>=]", flags=re.ASCII)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
@pass_eval_context
|
| 259 |
+
def do_xmlattr(
|
| 260 |
+
eval_ctx: "EvalContext", d: t.Mapping[str, t.Any], autospace: bool = True
|
| 261 |
+
) -> str:
|
| 262 |
+
"""Create an SGML/XML attribute string based on the items in a dict.
|
| 263 |
+
|
| 264 |
+
**Values** that are neither ``none`` nor ``undefined`` are automatically
|
| 265 |
+
escaped, safely allowing untrusted user input.
|
| 266 |
+
|
| 267 |
+
User input should not be used as **keys** to this filter. If any key
|
| 268 |
+
contains a space, ``/`` solidus, ``>`` greater-than sign, or ``=`` equals
|
| 269 |
+
sign, this fails with a ``ValueError``. Regardless of this, user input
|
| 270 |
+
should never be used as keys to this filter, or must be separately validated
|
| 271 |
+
first.
|
| 272 |
+
|
| 273 |
+
.. sourcecode:: html+jinja
|
| 274 |
+
|
| 275 |
+
<ul{{ {'class': 'my_list', 'missing': none,
|
| 276 |
+
'id': 'list-%d'|format(variable)}|xmlattr }}>
|
| 277 |
+
...
|
| 278 |
+
</ul>
|
| 279 |
+
|
| 280 |
+
Results in something like this:
|
| 281 |
+
|
| 282 |
+
.. sourcecode:: html
|
| 283 |
+
|
| 284 |
+
<ul class="my_list" id="list-42">
|
| 285 |
+
...
|
| 286 |
+
</ul>
|
| 287 |
+
|
| 288 |
+
As you can see it automatically prepends a space in front of the item
|
| 289 |
+
if the filter returned something unless the second parameter is false.
|
| 290 |
+
|
| 291 |
+
.. versionchanged:: 3.1.4
|
| 292 |
+
Keys with ``/`` solidus, ``>`` greater-than sign, or ``=`` equals sign
|
| 293 |
+
are not allowed.
|
| 294 |
+
|
| 295 |
+
.. versionchanged:: 3.1.3
|
| 296 |
+
Keys with spaces are not allowed.
|
| 297 |
+
"""
|
| 298 |
+
items = []
|
| 299 |
+
|
| 300 |
+
for key, value in d.items():
|
| 301 |
+
if value is None or isinstance(value, Undefined):
|
| 302 |
+
continue
|
| 303 |
+
|
| 304 |
+
if _attr_key_re.search(key) is not None:
|
| 305 |
+
raise ValueError(f"Invalid character in attribute name: {key!r}")
|
| 306 |
+
|
| 307 |
+
items.append(f'{escape(key)}="{escape(value)}"')
|
| 308 |
+
|
| 309 |
+
rv = " ".join(items)
|
| 310 |
+
|
| 311 |
+
if autospace and rv:
|
| 312 |
+
rv = " " + rv
|
| 313 |
+
|
| 314 |
+
if eval_ctx.autoescape:
|
| 315 |
+
rv = Markup(rv)
|
| 316 |
+
|
| 317 |
+
return rv
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def do_capitalize(s: str) -> str:
|
| 321 |
+
"""Capitalize a value. The first character will be uppercase, all others
|
| 322 |
+
lowercase.
|
| 323 |
+
"""
|
| 324 |
+
return soft_str(s).capitalize()
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
_word_beginning_split_re = re.compile(r"([-\s({\[<]+)")
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def do_title(s: str) -> str:
|
| 331 |
+
"""Return a titlecased version of the value. I.e. words will start with
|
| 332 |
+
uppercase letters, all remaining characters are lowercase.
|
| 333 |
+
"""
|
| 334 |
+
return "".join(
|
| 335 |
+
[
|
| 336 |
+
item[0].upper() + item[1:].lower()
|
| 337 |
+
for item in _word_beginning_split_re.split(soft_str(s))
|
| 338 |
+
if item
|
| 339 |
+
]
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def do_dictsort(
|
| 344 |
+
value: t.Mapping[K, V],
|
| 345 |
+
case_sensitive: bool = False,
|
| 346 |
+
by: 'te.Literal["key", "value"]' = "key",
|
| 347 |
+
reverse: bool = False,
|
| 348 |
+
) -> t.List[t.Tuple[K, V]]:
|
| 349 |
+
"""Sort a dict and yield (key, value) pairs. Python dicts may not
|
| 350 |
+
be in the order you want to display them in, so sort them first.
|
| 351 |
+
|
| 352 |
+
.. sourcecode:: jinja
|
| 353 |
+
|
| 354 |
+
{% for key, value in mydict|dictsort %}
|
| 355 |
+
sort the dict by key, case insensitive
|
| 356 |
+
|
| 357 |
+
{% for key, value in mydict|dictsort(reverse=true) %}
|
| 358 |
+
sort the dict by key, case insensitive, reverse order
|
| 359 |
+
|
| 360 |
+
{% for key, value in mydict|dictsort(true) %}
|
| 361 |
+
sort the dict by key, case sensitive
|
| 362 |
+
|
| 363 |
+
{% for key, value in mydict|dictsort(false, 'value') %}
|
| 364 |
+
sort the dict by value, case insensitive
|
| 365 |
+
"""
|
| 366 |
+
if by == "key":
|
| 367 |
+
pos = 0
|
| 368 |
+
elif by == "value":
|
| 369 |
+
pos = 1
|
| 370 |
+
else:
|
| 371 |
+
raise FilterArgumentError('You can only sort by either "key" or "value"')
|
| 372 |
+
|
| 373 |
+
def sort_func(item: t.Tuple[t.Any, t.Any]) -> t.Any:
|
| 374 |
+
value = item[pos]
|
| 375 |
+
|
| 376 |
+
if not case_sensitive:
|
| 377 |
+
value = ignore_case(value)
|
| 378 |
+
|
| 379 |
+
return value
|
| 380 |
+
|
| 381 |
+
return sorted(value.items(), key=sort_func, reverse=reverse)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
@pass_environment
|
| 385 |
+
def do_sort(
|
| 386 |
+
environment: "Environment",
|
| 387 |
+
value: "t.Iterable[V]",
|
| 388 |
+
reverse: bool = False,
|
| 389 |
+
case_sensitive: bool = False,
|
| 390 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
| 391 |
+
) -> "t.List[V]":
|
| 392 |
+
"""Sort an iterable using Python's :func:`sorted`.
|
| 393 |
+
|
| 394 |
+
.. sourcecode:: jinja
|
| 395 |
+
|
| 396 |
+
{% for city in cities|sort %}
|
| 397 |
+
...
|
| 398 |
+
{% endfor %}
|
| 399 |
+
|
| 400 |
+
:param reverse: Sort descending instead of ascending.
|
| 401 |
+
:param case_sensitive: When sorting strings, sort upper and lower
|
| 402 |
+
case separately.
|
| 403 |
+
:param attribute: When sorting objects or dicts, an attribute or
|
| 404 |
+
key to sort by. Can use dot notation like ``"address.city"``.
|
| 405 |
+
Can be a list of attributes like ``"age,name"``.
|
| 406 |
+
|
| 407 |
+
The sort is stable, it does not change the relative order of
|
| 408 |
+
elements that compare equal. This makes it is possible to chain
|
| 409 |
+
sorts on different attributes and ordering.
|
| 410 |
+
|
| 411 |
+
.. sourcecode:: jinja
|
| 412 |
+
|
| 413 |
+
{% for user in users|sort(attribute="name")
|
| 414 |
+
|sort(reverse=true, attribute="age") %}
|
| 415 |
+
...
|
| 416 |
+
{% endfor %}
|
| 417 |
+
|
| 418 |
+
As a shortcut to chaining when the direction is the same for all
|
| 419 |
+
attributes, pass a comma separate list of attributes.
|
| 420 |
+
|
| 421 |
+
.. sourcecode:: jinja
|
| 422 |
+
|
| 423 |
+
{% for user in users|sort(attribute="age,name") %}
|
| 424 |
+
...
|
| 425 |
+
{% endfor %}
|
| 426 |
+
|
| 427 |
+
.. versionchanged:: 2.11.0
|
| 428 |
+
The ``attribute`` parameter can be a comma separated list of
|
| 429 |
+
attributes, e.g. ``"age,name"``.
|
| 430 |
+
|
| 431 |
+
.. versionchanged:: 2.6
|
| 432 |
+
The ``attribute`` parameter was added.
|
| 433 |
+
"""
|
| 434 |
+
key_func = make_multi_attrgetter(
|
| 435 |
+
environment, attribute, postprocess=ignore_case if not case_sensitive else None
|
| 436 |
+
)
|
| 437 |
+
return sorted(value, key=key_func, reverse=reverse)
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
@pass_environment
|
| 441 |
+
def sync_do_unique(
|
| 442 |
+
environment: "Environment",
|
| 443 |
+
value: "t.Iterable[V]",
|
| 444 |
+
case_sensitive: bool = False,
|
| 445 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
| 446 |
+
) -> "t.Iterator[V]":
|
| 447 |
+
"""Returns a list of unique items from the given iterable.
|
| 448 |
+
|
| 449 |
+
.. sourcecode:: jinja
|
| 450 |
+
|
| 451 |
+
{{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }}
|
| 452 |
+
-> ['foo', 'bar', 'foobar']
|
| 453 |
+
|
| 454 |
+
The unique items are yielded in the same order as their first occurrence in
|
| 455 |
+
the iterable passed to the filter.
|
| 456 |
+
|
| 457 |
+
:param case_sensitive: Treat upper and lower case strings as distinct.
|
| 458 |
+
:param attribute: Filter objects with unique values for this attribute.
|
| 459 |
+
"""
|
| 460 |
+
getter = make_attrgetter(
|
| 461 |
+
environment, attribute, postprocess=ignore_case if not case_sensitive else None
|
| 462 |
+
)
|
| 463 |
+
seen = set()
|
| 464 |
+
|
| 465 |
+
for item in value:
|
| 466 |
+
key = getter(item)
|
| 467 |
+
|
| 468 |
+
if key not in seen:
|
| 469 |
+
seen.add(key)
|
| 470 |
+
yield item
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
@async_variant(sync_do_unique) # type: ignore
|
| 474 |
+
async def do_unique(
|
| 475 |
+
environment: "Environment",
|
| 476 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
| 477 |
+
case_sensitive: bool = False,
|
| 478 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
| 479 |
+
) -> "t.Iterator[V]":
|
| 480 |
+
return sync_do_unique(
|
| 481 |
+
environment, await auto_to_list(value), case_sensitive, attribute
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def _min_or_max(
|
| 486 |
+
environment: "Environment",
|
| 487 |
+
value: "t.Iterable[V]",
|
| 488 |
+
func: "t.Callable[..., V]",
|
| 489 |
+
case_sensitive: bool,
|
| 490 |
+
attribute: t.Optional[t.Union[str, int]],
|
| 491 |
+
) -> "t.Union[V, Undefined]":
|
| 492 |
+
it = iter(value)
|
| 493 |
+
|
| 494 |
+
try:
|
| 495 |
+
first = next(it)
|
| 496 |
+
except StopIteration:
|
| 497 |
+
return environment.undefined("No aggregated item, sequence was empty.")
|
| 498 |
+
|
| 499 |
+
key_func = make_attrgetter(
|
| 500 |
+
environment, attribute, postprocess=ignore_case if not case_sensitive else None
|
| 501 |
+
)
|
| 502 |
+
return func(chain([first], it), key=key_func)
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
@pass_environment
|
| 506 |
+
def do_min(
|
| 507 |
+
environment: "Environment",
|
| 508 |
+
value: "t.Iterable[V]",
|
| 509 |
+
case_sensitive: bool = False,
|
| 510 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
| 511 |
+
) -> "t.Union[V, Undefined]":
|
| 512 |
+
"""Return the smallest item from the sequence.
|
| 513 |
+
|
| 514 |
+
.. sourcecode:: jinja
|
| 515 |
+
|
| 516 |
+
{{ [1, 2, 3]|min }}
|
| 517 |
+
-> 1
|
| 518 |
+
|
| 519 |
+
:param case_sensitive: Treat upper and lower case strings as distinct.
|
| 520 |
+
:param attribute: Get the object with the min value of this attribute.
|
| 521 |
+
"""
|
| 522 |
+
return _min_or_max(environment, value, min, case_sensitive, attribute)
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
@pass_environment
|
| 526 |
+
def do_max(
|
| 527 |
+
environment: "Environment",
|
| 528 |
+
value: "t.Iterable[V]",
|
| 529 |
+
case_sensitive: bool = False,
|
| 530 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
| 531 |
+
) -> "t.Union[V, Undefined]":
|
| 532 |
+
"""Return the largest item from the sequence.
|
| 533 |
+
|
| 534 |
+
.. sourcecode:: jinja
|
| 535 |
+
|
| 536 |
+
{{ [1, 2, 3]|max }}
|
| 537 |
+
-> 3
|
| 538 |
+
|
| 539 |
+
:param case_sensitive: Treat upper and lower case strings as distinct.
|
| 540 |
+
:param attribute: Get the object with the max value of this attribute.
|
| 541 |
+
"""
|
| 542 |
+
return _min_or_max(environment, value, max, case_sensitive, attribute)
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
def do_default(
|
| 546 |
+
value: V,
|
| 547 |
+
default_value: V = "", # type: ignore
|
| 548 |
+
boolean: bool = False,
|
| 549 |
+
) -> V:
|
| 550 |
+
"""If the value is undefined it will return the passed default value,
|
| 551 |
+
otherwise the value of the variable:
|
| 552 |
+
|
| 553 |
+
.. sourcecode:: jinja
|
| 554 |
+
|
| 555 |
+
{{ my_variable|default('my_variable is not defined') }}
|
| 556 |
+
|
| 557 |
+
This will output the value of ``my_variable`` if the variable was
|
| 558 |
+
defined, otherwise ``'my_variable is not defined'``. If you want
|
| 559 |
+
to use default with variables that evaluate to false you have to
|
| 560 |
+
set the second parameter to `true`:
|
| 561 |
+
|
| 562 |
+
.. sourcecode:: jinja
|
| 563 |
+
|
| 564 |
+
{{ ''|default('the string was empty', true) }}
|
| 565 |
+
|
| 566 |
+
.. versionchanged:: 2.11
|
| 567 |
+
It's now possible to configure the :class:`~jinja2.Environment` with
|
| 568 |
+
:class:`~jinja2.ChainableUndefined` to make the `default` filter work
|
| 569 |
+
on nested elements and attributes that may contain undefined values
|
| 570 |
+
in the chain without getting an :exc:`~jinja2.UndefinedError`.
|
| 571 |
+
"""
|
| 572 |
+
if isinstance(value, Undefined) or (boolean and not value):
|
| 573 |
+
return default_value
|
| 574 |
+
|
| 575 |
+
return value
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
@pass_eval_context
|
| 579 |
+
def sync_do_join(
|
| 580 |
+
eval_ctx: "EvalContext",
|
| 581 |
+
value: t.Iterable[t.Any],
|
| 582 |
+
d: str = "",
|
| 583 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
| 584 |
+
) -> str:
|
| 585 |
+
"""Return a string which is the concatenation of the strings in the
|
| 586 |
+
sequence. The separator between elements is an empty string per
|
| 587 |
+
default, you can define it with the optional parameter:
|
| 588 |
+
|
| 589 |
+
.. sourcecode:: jinja
|
| 590 |
+
|
| 591 |
+
{{ [1, 2, 3]|join('|') }}
|
| 592 |
+
-> 1|2|3
|
| 593 |
+
|
| 594 |
+
{{ [1, 2, 3]|join }}
|
| 595 |
+
-> 123
|
| 596 |
+
|
| 597 |
+
It is also possible to join certain attributes of an object:
|
| 598 |
+
|
| 599 |
+
.. sourcecode:: jinja
|
| 600 |
+
|
| 601 |
+
{{ users|join(', ', attribute='username') }}
|
| 602 |
+
|
| 603 |
+
.. versionadded:: 2.6
|
| 604 |
+
The `attribute` parameter was added.
|
| 605 |
+
"""
|
| 606 |
+
if attribute is not None:
|
| 607 |
+
value = map(make_attrgetter(eval_ctx.environment, attribute), value)
|
| 608 |
+
|
| 609 |
+
# no automatic escaping? joining is a lot easier then
|
| 610 |
+
if not eval_ctx.autoescape:
|
| 611 |
+
return str(d).join(map(str, value))
|
| 612 |
+
|
| 613 |
+
# if the delimiter doesn't have an html representation we check
|
| 614 |
+
# if any of the items has. If yes we do a coercion to Markup
|
| 615 |
+
if not hasattr(d, "__html__"):
|
| 616 |
+
value = list(value)
|
| 617 |
+
do_escape = False
|
| 618 |
+
|
| 619 |
+
for idx, item in enumerate(value):
|
| 620 |
+
if hasattr(item, "__html__"):
|
| 621 |
+
do_escape = True
|
| 622 |
+
else:
|
| 623 |
+
value[idx] = str(item)
|
| 624 |
+
|
| 625 |
+
if do_escape:
|
| 626 |
+
d = escape(d)
|
| 627 |
+
else:
|
| 628 |
+
d = str(d)
|
| 629 |
+
|
| 630 |
+
return d.join(value)
|
| 631 |
+
|
| 632 |
+
# no html involved, to normal joining
|
| 633 |
+
return soft_str(d).join(map(soft_str, value))
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
@async_variant(sync_do_join) # type: ignore
|
| 637 |
+
async def do_join(
|
| 638 |
+
eval_ctx: "EvalContext",
|
| 639 |
+
value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],
|
| 640 |
+
d: str = "",
|
| 641 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
| 642 |
+
) -> str:
|
| 643 |
+
return sync_do_join(eval_ctx, await auto_to_list(value), d, attribute)
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
def do_center(value: str, width: int = 80) -> str:
|
| 647 |
+
"""Centers the value in a field of a given width."""
|
| 648 |
+
return soft_str(value).center(width)
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
@pass_environment
|
| 652 |
+
def sync_do_first(
|
| 653 |
+
environment: "Environment", seq: "t.Iterable[V]"
|
| 654 |
+
) -> "t.Union[V, Undefined]":
|
| 655 |
+
"""Return the first item of a sequence."""
|
| 656 |
+
try:
|
| 657 |
+
return next(iter(seq))
|
| 658 |
+
except StopIteration:
|
| 659 |
+
return environment.undefined("No first item, sequence was empty.")
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
@async_variant(sync_do_first) # type: ignore
|
| 663 |
+
async def do_first(
|
| 664 |
+
environment: "Environment", seq: "t.Union[t.AsyncIterable[V], t.Iterable[V]]"
|
| 665 |
+
) -> "t.Union[V, Undefined]":
|
| 666 |
+
try:
|
| 667 |
+
return await auto_aiter(seq).__anext__()
|
| 668 |
+
except StopAsyncIteration:
|
| 669 |
+
return environment.undefined("No first item, sequence was empty.")
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
@pass_environment
|
| 673 |
+
def do_last(
|
| 674 |
+
environment: "Environment", seq: "t.Reversible[V]"
|
| 675 |
+
) -> "t.Union[V, Undefined]":
|
| 676 |
+
"""Return the last item of a sequence.
|
| 677 |
+
|
| 678 |
+
Note: Does not work with generators. You may want to explicitly
|
| 679 |
+
convert it to a list:
|
| 680 |
+
|
| 681 |
+
.. sourcecode:: jinja
|
| 682 |
+
|
| 683 |
+
{{ data | selectattr('name', '==', 'Jinja') | list | last }}
|
| 684 |
+
"""
|
| 685 |
+
try:
|
| 686 |
+
return next(iter(reversed(seq)))
|
| 687 |
+
except StopIteration:
|
| 688 |
+
return environment.undefined("No last item, sequence was empty.")
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
# No async do_last, it may not be safe in async mode.
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
@pass_context
|
| 695 |
+
def do_random(context: "Context", seq: "t.Sequence[V]") -> "t.Union[V, Undefined]":
|
| 696 |
+
"""Return a random item from the sequence."""
|
| 697 |
+
try:
|
| 698 |
+
return random.choice(seq)
|
| 699 |
+
except IndexError:
|
| 700 |
+
return context.environment.undefined("No random item, sequence was empty.")
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
def do_filesizeformat(value: t.Union[str, float, int], binary: bool = False) -> str:
|
| 704 |
+
"""Format the value like a 'human-readable' file size (i.e. 13 kB,
|
| 705 |
+
4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,
|
| 706 |
+
Giga, etc.), if the second parameter is set to `True` the binary
|
| 707 |
+
prefixes are used (Mebi, Gibi).
|
| 708 |
+
"""
|
| 709 |
+
bytes = float(value)
|
| 710 |
+
base = 1024 if binary else 1000
|
| 711 |
+
prefixes = [
|
| 712 |
+
("KiB" if binary else "kB"),
|
| 713 |
+
("MiB" if binary else "MB"),
|
| 714 |
+
("GiB" if binary else "GB"),
|
| 715 |
+
("TiB" if binary else "TB"),
|
| 716 |
+
("PiB" if binary else "PB"),
|
| 717 |
+
("EiB" if binary else "EB"),
|
| 718 |
+
("ZiB" if binary else "ZB"),
|
| 719 |
+
("YiB" if binary else "YB"),
|
| 720 |
+
]
|
| 721 |
+
|
| 722 |
+
if bytes == 1:
|
| 723 |
+
return "1 Byte"
|
| 724 |
+
elif bytes < base:
|
| 725 |
+
return f"{int(bytes)} Bytes"
|
| 726 |
+
else:
|
| 727 |
+
for i, prefix in enumerate(prefixes):
|
| 728 |
+
unit = base ** (i + 2)
|
| 729 |
+
|
| 730 |
+
if bytes < unit:
|
| 731 |
+
return f"{base * bytes / unit:.1f} {prefix}"
|
| 732 |
+
|
| 733 |
+
return f"{base * bytes / unit:.1f} {prefix}"
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
def do_pprint(value: t.Any) -> str:
|
| 737 |
+
"""Pretty print a variable. Useful for debugging."""
|
| 738 |
+
return pformat(value)
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
_uri_scheme_re = re.compile(r"^([\w.+-]{2,}:(/){0,2})$")
|
| 742 |
+
|
| 743 |
+
|
| 744 |
+
@pass_eval_context
|
| 745 |
+
def do_urlize(
|
| 746 |
+
eval_ctx: "EvalContext",
|
| 747 |
+
value: str,
|
| 748 |
+
trim_url_limit: t.Optional[int] = None,
|
| 749 |
+
nofollow: bool = False,
|
| 750 |
+
target: t.Optional[str] = None,
|
| 751 |
+
rel: t.Optional[str] = None,
|
| 752 |
+
extra_schemes: t.Optional[t.Iterable[str]] = None,
|
| 753 |
+
) -> str:
|
| 754 |
+
"""Convert URLs in text into clickable links.
|
| 755 |
+
|
| 756 |
+
This may not recognize links in some situations. Usually, a more
|
| 757 |
+
comprehensive formatter, such as a Markdown library, is a better
|
| 758 |
+
choice.
|
| 759 |
+
|
| 760 |
+
Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email
|
| 761 |
+
addresses. Links with trailing punctuation (periods, commas, closing
|
| 762 |
+
parentheses) and leading punctuation (opening parentheses) are
|
| 763 |
+
recognized excluding the punctuation. Email addresses that include
|
| 764 |
+
header fields are not recognized (for example,
|
| 765 |
+
``mailto:address@example.com?cc=copy@example.com``).
|
| 766 |
+
|
| 767 |
+
:param value: Original text containing URLs to link.
|
| 768 |
+
:param trim_url_limit: Shorten displayed URL values to this length.
|
| 769 |
+
:param nofollow: Add the ``rel=nofollow`` attribute to links.
|
| 770 |
+
:param target: Add the ``target`` attribute to links.
|
| 771 |
+
:param rel: Add the ``rel`` attribute to links.
|
| 772 |
+
:param extra_schemes: Recognize URLs that start with these schemes
|
| 773 |
+
in addition to the default behavior. Defaults to
|
| 774 |
+
``env.policies["urlize.extra_schemes"]``, which defaults to no
|
| 775 |
+
extra schemes.
|
| 776 |
+
|
| 777 |
+
.. versionchanged:: 3.0
|
| 778 |
+
The ``extra_schemes`` parameter was added.
|
| 779 |
+
|
| 780 |
+
.. versionchanged:: 3.0
|
| 781 |
+
Generate ``https://`` links for URLs without a scheme.
|
| 782 |
+
|
| 783 |
+
.. versionchanged:: 3.0
|
| 784 |
+
The parsing rules were updated. Recognize email addresses with
|
| 785 |
+
or without the ``mailto:`` scheme. Validate IP addresses. Ignore
|
| 786 |
+
parentheses and brackets in more cases.
|
| 787 |
+
|
| 788 |
+
.. versionchanged:: 2.8
|
| 789 |
+
The ``target`` parameter was added.
|
| 790 |
+
"""
|
| 791 |
+
policies = eval_ctx.environment.policies
|
| 792 |
+
rel_parts = set((rel or "").split())
|
| 793 |
+
|
| 794 |
+
if nofollow:
|
| 795 |
+
rel_parts.add("nofollow")
|
| 796 |
+
|
| 797 |
+
rel_parts.update((policies["urlize.rel"] or "").split())
|
| 798 |
+
rel = " ".join(sorted(rel_parts)) or None
|
| 799 |
+
|
| 800 |
+
if target is None:
|
| 801 |
+
target = policies["urlize.target"]
|
| 802 |
+
|
| 803 |
+
if extra_schemes is None:
|
| 804 |
+
extra_schemes = policies["urlize.extra_schemes"] or ()
|
| 805 |
+
|
| 806 |
+
for scheme in extra_schemes:
|
| 807 |
+
if _uri_scheme_re.fullmatch(scheme) is None:
|
| 808 |
+
raise FilterArgumentError(f"{scheme!r} is not a valid URI scheme prefix.")
|
| 809 |
+
|
| 810 |
+
rv = urlize(
|
| 811 |
+
value,
|
| 812 |
+
trim_url_limit=trim_url_limit,
|
| 813 |
+
rel=rel,
|
| 814 |
+
target=target,
|
| 815 |
+
extra_schemes=extra_schemes,
|
| 816 |
+
)
|
| 817 |
+
|
| 818 |
+
if eval_ctx.autoescape:
|
| 819 |
+
rv = Markup(rv)
|
| 820 |
+
|
| 821 |
+
return rv
|
| 822 |
+
|
| 823 |
+
|
| 824 |
+
def do_indent(
|
| 825 |
+
s: str, width: t.Union[int, str] = 4, first: bool = False, blank: bool = False
|
| 826 |
+
) -> str:
|
| 827 |
+
"""Return a copy of the string with each line indented by 4 spaces. The
|
| 828 |
+
first line and blank lines are not indented by default.
|
| 829 |
+
|
| 830 |
+
:param width: Number of spaces, or a string, to indent by.
|
| 831 |
+
:param first: Don't skip indenting the first line.
|
| 832 |
+
:param blank: Don't skip indenting empty lines.
|
| 833 |
+
|
| 834 |
+
.. versionchanged:: 3.0
|
| 835 |
+
``width`` can be a string.
|
| 836 |
+
|
| 837 |
+
.. versionchanged:: 2.10
|
| 838 |
+
Blank lines are not indented by default.
|
| 839 |
+
|
| 840 |
+
Rename the ``indentfirst`` argument to ``first``.
|
| 841 |
+
"""
|
| 842 |
+
if isinstance(width, str):
|
| 843 |
+
indention = width
|
| 844 |
+
else:
|
| 845 |
+
indention = " " * width
|
| 846 |
+
|
| 847 |
+
newline = "\n"
|
| 848 |
+
|
| 849 |
+
if isinstance(s, Markup):
|
| 850 |
+
indention = Markup(indention)
|
| 851 |
+
newline = Markup(newline)
|
| 852 |
+
|
| 853 |
+
s += newline # this quirk is necessary for splitlines method
|
| 854 |
+
|
| 855 |
+
if blank:
|
| 856 |
+
rv = (newline + indention).join(s.splitlines())
|
| 857 |
+
else:
|
| 858 |
+
lines = s.splitlines()
|
| 859 |
+
rv = lines.pop(0)
|
| 860 |
+
|
| 861 |
+
if lines:
|
| 862 |
+
rv += newline + newline.join(
|
| 863 |
+
indention + line if line else line for line in lines
|
| 864 |
+
)
|
| 865 |
+
|
| 866 |
+
if first:
|
| 867 |
+
rv = indention + rv
|
| 868 |
+
|
| 869 |
+
return rv
|
| 870 |
+
|
| 871 |
+
|
| 872 |
+
@pass_environment
|
| 873 |
+
def do_truncate(
|
| 874 |
+
env: "Environment",
|
| 875 |
+
s: str,
|
| 876 |
+
length: int = 255,
|
| 877 |
+
killwords: bool = False,
|
| 878 |
+
end: str = "...",
|
| 879 |
+
leeway: t.Optional[int] = None,
|
| 880 |
+
) -> str:
|
| 881 |
+
"""Return a truncated copy of the string. The length is specified
|
| 882 |
+
with the first parameter which defaults to ``255``. If the second
|
| 883 |
+
parameter is ``true`` the filter will cut the text at length. Otherwise
|
| 884 |
+
it will discard the last word. If the text was in fact
|
| 885 |
+
truncated it will append an ellipsis sign (``"..."``). If you want a
|
| 886 |
+
different ellipsis sign than ``"..."`` you can specify it using the
|
| 887 |
+
third parameter. Strings that only exceed the length by the tolerance
|
| 888 |
+
margin given in the fourth parameter will not be truncated.
|
| 889 |
+
|
| 890 |
+
.. sourcecode:: jinja
|
| 891 |
+
|
| 892 |
+
{{ "foo bar baz qux"|truncate(9) }}
|
| 893 |
+
-> "foo..."
|
| 894 |
+
{{ "foo bar baz qux"|truncate(9, True) }}
|
| 895 |
+
-> "foo ba..."
|
| 896 |
+
{{ "foo bar baz qux"|truncate(11) }}
|
| 897 |
+
-> "foo bar baz qux"
|
| 898 |
+
{{ "foo bar baz qux"|truncate(11, False, '...', 0) }}
|
| 899 |
+
-> "foo bar..."
|
| 900 |
+
|
| 901 |
+
The default leeway on newer Jinja versions is 5 and was 0 before but
|
| 902 |
+
can be reconfigured globally.
|
| 903 |
+
"""
|
| 904 |
+
if leeway is None:
|
| 905 |
+
leeway = env.policies["truncate.leeway"]
|
| 906 |
+
|
| 907 |
+
assert length >= len(end), f"expected length >= {len(end)}, got {length}"
|
| 908 |
+
assert leeway >= 0, f"expected leeway >= 0, got {leeway}"
|
| 909 |
+
|
| 910 |
+
if len(s) <= length + leeway:
|
| 911 |
+
return s
|
| 912 |
+
|
| 913 |
+
if killwords:
|
| 914 |
+
return s[: length - len(end)] + end
|
| 915 |
+
|
| 916 |
+
result = s[: length - len(end)].rsplit(" ", 1)[0]
|
| 917 |
+
return result + end
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
@pass_environment
|
| 921 |
+
def do_wordwrap(
|
| 922 |
+
environment: "Environment",
|
| 923 |
+
s: str,
|
| 924 |
+
width: int = 79,
|
| 925 |
+
break_long_words: bool = True,
|
| 926 |
+
wrapstring: t.Optional[str] = None,
|
| 927 |
+
break_on_hyphens: bool = True,
|
| 928 |
+
) -> str:
|
| 929 |
+
"""Wrap a string to the given width. Existing newlines are treated
|
| 930 |
+
as paragraphs to be wrapped separately.
|
| 931 |
+
|
| 932 |
+
:param s: Original text to wrap.
|
| 933 |
+
:param width: Maximum length of wrapped lines.
|
| 934 |
+
:param break_long_words: If a word is longer than ``width``, break
|
| 935 |
+
it across lines.
|
| 936 |
+
:param break_on_hyphens: If a word contains hyphens, it may be split
|
| 937 |
+
across lines.
|
| 938 |
+
:param wrapstring: String to join each wrapped line. Defaults to
|
| 939 |
+
:attr:`Environment.newline_sequence`.
|
| 940 |
+
|
| 941 |
+
.. versionchanged:: 2.11
|
| 942 |
+
Existing newlines are treated as paragraphs wrapped separately.
|
| 943 |
+
|
| 944 |
+
.. versionchanged:: 2.11
|
| 945 |
+
Added the ``break_on_hyphens`` parameter.
|
| 946 |
+
|
| 947 |
+
.. versionchanged:: 2.7
|
| 948 |
+
Added the ``wrapstring`` parameter.
|
| 949 |
+
"""
|
| 950 |
+
import textwrap
|
| 951 |
+
|
| 952 |
+
if wrapstring is None:
|
| 953 |
+
wrapstring = environment.newline_sequence
|
| 954 |
+
|
| 955 |
+
# textwrap.wrap doesn't consider existing newlines when wrapping.
|
| 956 |
+
# If the string has a newline before width, wrap will still insert
|
| 957 |
+
# a newline at width, resulting in a short line. Instead, split and
|
| 958 |
+
# wrap each paragraph individually.
|
| 959 |
+
return wrapstring.join(
|
| 960 |
+
[
|
| 961 |
+
wrapstring.join(
|
| 962 |
+
textwrap.wrap(
|
| 963 |
+
line,
|
| 964 |
+
width=width,
|
| 965 |
+
expand_tabs=False,
|
| 966 |
+
replace_whitespace=False,
|
| 967 |
+
break_long_words=break_long_words,
|
| 968 |
+
break_on_hyphens=break_on_hyphens,
|
| 969 |
+
)
|
| 970 |
+
)
|
| 971 |
+
for line in s.splitlines()
|
| 972 |
+
]
|
| 973 |
+
)
|
| 974 |
+
|
| 975 |
+
|
| 976 |
+
_word_re = re.compile(r"\w+")
|
| 977 |
+
|
| 978 |
+
|
| 979 |
+
def do_wordcount(s: str) -> int:
|
| 980 |
+
"""Count the words in that string."""
|
| 981 |
+
return len(_word_re.findall(soft_str(s)))
|
| 982 |
+
|
| 983 |
+
|
| 984 |
+
def do_int(value: t.Any, default: int = 0, base: int = 10) -> int:
|
| 985 |
+
"""Convert the value into an integer. If the
|
| 986 |
+
conversion doesn't work it will return ``0``. You can
|
| 987 |
+
override this default using the first parameter. You
|
| 988 |
+
can also override the default base (10) in the second
|
| 989 |
+
parameter, which handles input with prefixes such as
|
| 990 |
+
0b, 0o and 0x for bases 2, 8 and 16 respectively.
|
| 991 |
+
The base is ignored for decimal numbers and non-string values.
|
| 992 |
+
"""
|
| 993 |
+
try:
|
| 994 |
+
if isinstance(value, str):
|
| 995 |
+
return int(value, base)
|
| 996 |
+
|
| 997 |
+
return int(value)
|
| 998 |
+
except (TypeError, ValueError):
|
| 999 |
+
# this quirk is necessary so that "42.23"|int gives 42.
|
| 1000 |
+
try:
|
| 1001 |
+
return int(float(value))
|
| 1002 |
+
except (TypeError, ValueError, OverflowError):
|
| 1003 |
+
return default
|
| 1004 |
+
|
| 1005 |
+
|
| 1006 |
+
def do_float(value: t.Any, default: float = 0.0) -> float:
|
| 1007 |
+
"""Convert the value into a floating point number. If the
|
| 1008 |
+
conversion doesn't work it will return ``0.0``. You can
|
| 1009 |
+
override this default using the first parameter.
|
| 1010 |
+
"""
|
| 1011 |
+
try:
|
| 1012 |
+
return float(value)
|
| 1013 |
+
except (TypeError, ValueError):
|
| 1014 |
+
return default
|
| 1015 |
+
|
| 1016 |
+
|
| 1017 |
+
def do_format(value: str, *args: t.Any, **kwargs: t.Any) -> str:
|
| 1018 |
+
"""Apply the given values to a `printf-style`_ format string, like
|
| 1019 |
+
``string % values``.
|
| 1020 |
+
|
| 1021 |
+
.. sourcecode:: jinja
|
| 1022 |
+
|
| 1023 |
+
{{ "%s, %s!"|format(greeting, name) }}
|
| 1024 |
+
Hello, World!
|
| 1025 |
+
|
| 1026 |
+
In most cases it should be more convenient and efficient to use the
|
| 1027 |
+
``%`` operator or :meth:`str.format`.
|
| 1028 |
+
|
| 1029 |
+
.. code-block:: text
|
| 1030 |
+
|
| 1031 |
+
{{ "%s, %s!" % (greeting, name) }}
|
| 1032 |
+
{{ "{}, {}!".format(greeting, name) }}
|
| 1033 |
+
|
| 1034 |
+
.. _printf-style: https://docs.python.org/library/stdtypes.html
|
| 1035 |
+
#printf-style-string-formatting
|
| 1036 |
+
"""
|
| 1037 |
+
if args and kwargs:
|
| 1038 |
+
raise FilterArgumentError(
|
| 1039 |
+
"can't handle positional and keyword arguments at the same time"
|
| 1040 |
+
)
|
| 1041 |
+
|
| 1042 |
+
return soft_str(value) % (kwargs or args)
|
| 1043 |
+
|
| 1044 |
+
|
| 1045 |
+
def do_trim(value: str, chars: t.Optional[str] = None) -> str:
|
| 1046 |
+
"""Strip leading and trailing characters, by default whitespace."""
|
| 1047 |
+
return soft_str(value).strip(chars)
|
| 1048 |
+
|
| 1049 |
+
|
| 1050 |
+
def do_striptags(value: "t.Union[str, HasHTML]") -> str:
|
| 1051 |
+
"""Strip SGML/XML tags and replace adjacent whitespace by one space."""
|
| 1052 |
+
if hasattr(value, "__html__"):
|
| 1053 |
+
value = t.cast("HasHTML", value).__html__()
|
| 1054 |
+
|
| 1055 |
+
return Markup(str(value)).striptags()
|
| 1056 |
+
|
| 1057 |
+
|
| 1058 |
+
def sync_do_slice(
|
| 1059 |
+
value: "t.Collection[V]", slices: int, fill_with: "t.Optional[V]" = None
|
| 1060 |
+
) -> "t.Iterator[t.List[V]]":
|
| 1061 |
+
"""Slice an iterator and return a list of lists containing
|
| 1062 |
+
those items. Useful if you want to create a div containing
|
| 1063 |
+
three ul tags that represent columns:
|
| 1064 |
+
|
| 1065 |
+
.. sourcecode:: html+jinja
|
| 1066 |
+
|
| 1067 |
+
<div class="columnwrapper">
|
| 1068 |
+
{%- for column in items|slice(3) %}
|
| 1069 |
+
<ul class="column-{{ loop.index }}">
|
| 1070 |
+
{%- for item in column %}
|
| 1071 |
+
<li>{{ item }}</li>
|
| 1072 |
+
{%- endfor %}
|
| 1073 |
+
</ul>
|
| 1074 |
+
{%- endfor %}
|
| 1075 |
+
</div>
|
| 1076 |
+
|
| 1077 |
+
If you pass it a second argument it's used to fill missing
|
| 1078 |
+
values on the last iteration.
|
| 1079 |
+
"""
|
| 1080 |
+
seq = list(value)
|
| 1081 |
+
length = len(seq)
|
| 1082 |
+
items_per_slice = length // slices
|
| 1083 |
+
slices_with_extra = length % slices
|
| 1084 |
+
offset = 0
|
| 1085 |
+
|
| 1086 |
+
for slice_number in range(slices):
|
| 1087 |
+
start = offset + slice_number * items_per_slice
|
| 1088 |
+
|
| 1089 |
+
if slice_number < slices_with_extra:
|
| 1090 |
+
offset += 1
|
| 1091 |
+
|
| 1092 |
+
end = offset + (slice_number + 1) * items_per_slice
|
| 1093 |
+
tmp = seq[start:end]
|
| 1094 |
+
|
| 1095 |
+
if fill_with is not None and slice_number >= slices_with_extra:
|
| 1096 |
+
tmp.append(fill_with)
|
| 1097 |
+
|
| 1098 |
+
yield tmp
|
| 1099 |
+
|
| 1100 |
+
|
| 1101 |
+
@async_variant(sync_do_slice) # type: ignore
|
| 1102 |
+
async def do_slice(
|
| 1103 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
| 1104 |
+
slices: int,
|
| 1105 |
+
fill_with: t.Optional[t.Any] = None,
|
| 1106 |
+
) -> "t.Iterator[t.List[V]]":
|
| 1107 |
+
return sync_do_slice(await auto_to_list(value), slices, fill_with)
|
| 1108 |
+
|
| 1109 |
+
|
| 1110 |
+
def do_batch(
|
| 1111 |
+
value: "t.Iterable[V]", linecount: int, fill_with: "t.Optional[V]" = None
|
| 1112 |
+
) -> "t.Iterator[t.List[V]]":
|
| 1113 |
+
"""
|
| 1114 |
+
A filter that batches items. It works pretty much like `slice`
|
| 1115 |
+
just the other way round. It returns a list of lists with the
|
| 1116 |
+
given number of items. If you provide a second parameter this
|
| 1117 |
+
is used to fill up missing items. See this example:
|
| 1118 |
+
|
| 1119 |
+
.. sourcecode:: html+jinja
|
| 1120 |
+
|
| 1121 |
+
<table>
|
| 1122 |
+
{%- for row in items|batch(3, ' ') %}
|
| 1123 |
+
<tr>
|
| 1124 |
+
{%- for column in row %}
|
| 1125 |
+
<td>{{ column }}</td>
|
| 1126 |
+
{%- endfor %}
|
| 1127 |
+
</tr>
|
| 1128 |
+
{%- endfor %}
|
| 1129 |
+
</table>
|
| 1130 |
+
"""
|
| 1131 |
+
tmp: t.List[V] = []
|
| 1132 |
+
|
| 1133 |
+
for item in value:
|
| 1134 |
+
if len(tmp) == linecount:
|
| 1135 |
+
yield tmp
|
| 1136 |
+
tmp = []
|
| 1137 |
+
|
| 1138 |
+
tmp.append(item)
|
| 1139 |
+
|
| 1140 |
+
if tmp:
|
| 1141 |
+
if fill_with is not None and len(tmp) < linecount:
|
| 1142 |
+
tmp += [fill_with] * (linecount - len(tmp))
|
| 1143 |
+
|
| 1144 |
+
yield tmp
|
| 1145 |
+
|
| 1146 |
+
|
| 1147 |
+
def do_round(
|
| 1148 |
+
value: float,
|
| 1149 |
+
precision: int = 0,
|
| 1150 |
+
method: 'te.Literal["common", "ceil", "floor"]' = "common",
|
| 1151 |
+
) -> float:
|
| 1152 |
+
"""Round the number to a given precision. The first
|
| 1153 |
+
parameter specifies the precision (default is ``0``), the
|
| 1154 |
+
second the rounding method:
|
| 1155 |
+
|
| 1156 |
+
- ``'common'`` rounds either up or down
|
| 1157 |
+
- ``'ceil'`` always rounds up
|
| 1158 |
+
- ``'floor'`` always rounds down
|
| 1159 |
+
|
| 1160 |
+
If you don't specify a method ``'common'`` is used.
|
| 1161 |
+
|
| 1162 |
+
.. sourcecode:: jinja
|
| 1163 |
+
|
| 1164 |
+
{{ 42.55|round }}
|
| 1165 |
+
-> 43.0
|
| 1166 |
+
{{ 42.55|round(1, 'floor') }}
|
| 1167 |
+
-> 42.5
|
| 1168 |
+
|
| 1169 |
+
Note that even if rounded to 0 precision, a float is returned. If
|
| 1170 |
+
you need a real integer, pipe it through `int`:
|
| 1171 |
+
|
| 1172 |
+
.. sourcecode:: jinja
|
| 1173 |
+
|
| 1174 |
+
{{ 42.55|round|int }}
|
| 1175 |
+
-> 43
|
| 1176 |
+
"""
|
| 1177 |
+
if method not in {"common", "ceil", "floor"}:
|
| 1178 |
+
raise FilterArgumentError("method must be common, ceil or floor")
|
| 1179 |
+
|
| 1180 |
+
if method == "common":
|
| 1181 |
+
return round(value, precision)
|
| 1182 |
+
|
| 1183 |
+
func = getattr(math, method)
|
| 1184 |
+
return t.cast(float, func(value * (10**precision)) / (10**precision))
|
| 1185 |
+
|
| 1186 |
+
|
| 1187 |
+
class _GroupTuple(t.NamedTuple):
|
| 1188 |
+
grouper: t.Any
|
| 1189 |
+
list: t.List[t.Any]
|
| 1190 |
+
|
| 1191 |
+
# Use the regular tuple repr to hide this subclass if users print
|
| 1192 |
+
# out the value during debugging.
|
| 1193 |
+
def __repr__(self) -> str:
|
| 1194 |
+
return tuple.__repr__(self)
|
| 1195 |
+
|
| 1196 |
+
def __str__(self) -> str:
|
| 1197 |
+
return tuple.__str__(self)
|
| 1198 |
+
|
| 1199 |
+
|
| 1200 |
+
@pass_environment
|
| 1201 |
+
def sync_do_groupby(
|
| 1202 |
+
environment: "Environment",
|
| 1203 |
+
value: "t.Iterable[V]",
|
| 1204 |
+
attribute: t.Union[str, int],
|
| 1205 |
+
default: t.Optional[t.Any] = None,
|
| 1206 |
+
case_sensitive: bool = False,
|
| 1207 |
+
) -> "t.List[_GroupTuple]":
|
| 1208 |
+
"""Group a sequence of objects by an attribute using Python's
|
| 1209 |
+
:func:`itertools.groupby`. The attribute can use dot notation for
|
| 1210 |
+
nested access, like ``"address.city"``. Unlike Python's ``groupby``,
|
| 1211 |
+
the values are sorted first so only one group is returned for each
|
| 1212 |
+
unique value.
|
| 1213 |
+
|
| 1214 |
+
For example, a list of ``User`` objects with a ``city`` attribute
|
| 1215 |
+
can be rendered in groups. In this example, ``grouper`` refers to
|
| 1216 |
+
the ``city`` value of the group.
|
| 1217 |
+
|
| 1218 |
+
.. sourcecode:: html+jinja
|
| 1219 |
+
|
| 1220 |
+
<ul>{% for city, items in users|groupby("city") %}
|
| 1221 |
+
<li>{{ city }}
|
| 1222 |
+
<ul>{% for user in items %}
|
| 1223 |
+
<li>{{ user.name }}
|
| 1224 |
+
{% endfor %}</ul>
|
| 1225 |
+
</li>
|
| 1226 |
+
{% endfor %}</ul>
|
| 1227 |
+
|
| 1228 |
+
``groupby`` yields namedtuples of ``(grouper, list)``, which
|
| 1229 |
+
can be used instead of the tuple unpacking above. ``grouper`` is the
|
| 1230 |
+
value of the attribute, and ``list`` is the items with that value.
|
| 1231 |
+
|
| 1232 |
+
.. sourcecode:: html+jinja
|
| 1233 |
+
|
| 1234 |
+
<ul>{% for group in users|groupby("city") %}
|
| 1235 |
+
<li>{{ group.grouper }}: {{ group.list|join(", ") }}
|
| 1236 |
+
{% endfor %}</ul>
|
| 1237 |
+
|
| 1238 |
+
You can specify a ``default`` value to use if an object in the list
|
| 1239 |
+
does not have the given attribute.
|
| 1240 |
+
|
| 1241 |
+
.. sourcecode:: jinja
|
| 1242 |
+
|
| 1243 |
+
<ul>{% for city, items in users|groupby("city", default="NY") %}
|
| 1244 |
+
<li>{{ city }}: {{ items|map(attribute="name")|join(", ") }}</li>
|
| 1245 |
+
{% endfor %}</ul>
|
| 1246 |
+
|
| 1247 |
+
Like the :func:`~jinja-filters.sort` filter, sorting and grouping is
|
| 1248 |
+
case-insensitive by default. The ``key`` for each group will have
|
| 1249 |
+
the case of the first item in that group of values. For example, if
|
| 1250 |
+
a list of users has cities ``["CA", "NY", "ca"]``, the "CA" group
|
| 1251 |
+
will have two values. This can be disabled by passing
|
| 1252 |
+
``case_sensitive=True``.
|
| 1253 |
+
|
| 1254 |
+
.. versionchanged:: 3.1
|
| 1255 |
+
Added the ``case_sensitive`` parameter. Sorting and grouping is
|
| 1256 |
+
case-insensitive by default, matching other filters that do
|
| 1257 |
+
comparisons.
|
| 1258 |
+
|
| 1259 |
+
.. versionchanged:: 3.0
|
| 1260 |
+
Added the ``default`` parameter.
|
| 1261 |
+
|
| 1262 |
+
.. versionchanged:: 2.6
|
| 1263 |
+
The attribute supports dot notation for nested access.
|
| 1264 |
+
"""
|
| 1265 |
+
expr = make_attrgetter(
|
| 1266 |
+
environment,
|
| 1267 |
+
attribute,
|
| 1268 |
+
postprocess=ignore_case if not case_sensitive else None,
|
| 1269 |
+
default=default,
|
| 1270 |
+
)
|
| 1271 |
+
out = [
|
| 1272 |
+
_GroupTuple(key, list(values))
|
| 1273 |
+
for key, values in groupby(sorted(value, key=expr), expr)
|
| 1274 |
+
]
|
| 1275 |
+
|
| 1276 |
+
if not case_sensitive:
|
| 1277 |
+
# Return the real key from the first value instead of the lowercase key.
|
| 1278 |
+
output_expr = make_attrgetter(environment, attribute, default=default)
|
| 1279 |
+
out = [_GroupTuple(output_expr(values[0]), values) for _, values in out]
|
| 1280 |
+
|
| 1281 |
+
return out
|
| 1282 |
+
|
| 1283 |
+
|
| 1284 |
+
@async_variant(sync_do_groupby) # type: ignore
|
| 1285 |
+
async def do_groupby(
|
| 1286 |
+
environment: "Environment",
|
| 1287 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
| 1288 |
+
attribute: t.Union[str, int],
|
| 1289 |
+
default: t.Optional[t.Any] = None,
|
| 1290 |
+
case_sensitive: bool = False,
|
| 1291 |
+
) -> "t.List[_GroupTuple]":
|
| 1292 |
+
expr = make_attrgetter(
|
| 1293 |
+
environment,
|
| 1294 |
+
attribute,
|
| 1295 |
+
postprocess=ignore_case if not case_sensitive else None,
|
| 1296 |
+
default=default,
|
| 1297 |
+
)
|
| 1298 |
+
out = [
|
| 1299 |
+
_GroupTuple(key, await auto_to_list(values))
|
| 1300 |
+
for key, values in groupby(sorted(await auto_to_list(value), key=expr), expr)
|
| 1301 |
+
]
|
| 1302 |
+
|
| 1303 |
+
if not case_sensitive:
|
| 1304 |
+
# Return the real key from the first value instead of the lowercase key.
|
| 1305 |
+
output_expr = make_attrgetter(environment, attribute, default=default)
|
| 1306 |
+
out = [_GroupTuple(output_expr(values[0]), values) for _, values in out]
|
| 1307 |
+
|
| 1308 |
+
return out
|
| 1309 |
+
|
| 1310 |
+
|
| 1311 |
+
@pass_environment
|
| 1312 |
+
def sync_do_sum(
|
| 1313 |
+
environment: "Environment",
|
| 1314 |
+
iterable: "t.Iterable[V]",
|
| 1315 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
| 1316 |
+
start: V = 0, # type: ignore
|
| 1317 |
+
) -> V:
|
| 1318 |
+
"""Returns the sum of a sequence of numbers plus the value of parameter
|
| 1319 |
+
'start' (which defaults to 0). When the sequence is empty it returns
|
| 1320 |
+
start.
|
| 1321 |
+
|
| 1322 |
+
It is also possible to sum up only certain attributes:
|
| 1323 |
+
|
| 1324 |
+
.. sourcecode:: jinja
|
| 1325 |
+
|
| 1326 |
+
Total: {{ items|sum(attribute='price') }}
|
| 1327 |
+
|
| 1328 |
+
.. versionchanged:: 2.6
|
| 1329 |
+
The ``attribute`` parameter was added to allow summing up over
|
| 1330 |
+
attributes. Also the ``start`` parameter was moved on to the right.
|
| 1331 |
+
"""
|
| 1332 |
+
if attribute is not None:
|
| 1333 |
+
iterable = map(make_attrgetter(environment, attribute), iterable)
|
| 1334 |
+
|
| 1335 |
+
return sum(iterable, start) # type: ignore[no-any-return, call-overload]
|
| 1336 |
+
|
| 1337 |
+
|
| 1338 |
+
@async_variant(sync_do_sum) # type: ignore
|
| 1339 |
+
async def do_sum(
|
| 1340 |
+
environment: "Environment",
|
| 1341 |
+
iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
| 1342 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
| 1343 |
+
start: V = 0, # type: ignore
|
| 1344 |
+
) -> V:
|
| 1345 |
+
rv = start
|
| 1346 |
+
|
| 1347 |
+
if attribute is not None:
|
| 1348 |
+
func = make_attrgetter(environment, attribute)
|
| 1349 |
+
else:
|
| 1350 |
+
|
| 1351 |
+
def func(x: V) -> V:
|
| 1352 |
+
return x
|
| 1353 |
+
|
| 1354 |
+
async for item in auto_aiter(iterable):
|
| 1355 |
+
rv += func(item)
|
| 1356 |
+
|
| 1357 |
+
return rv
|
| 1358 |
+
|
| 1359 |
+
|
| 1360 |
+
def sync_do_list(value: "t.Iterable[V]") -> "t.List[V]":
|
| 1361 |
+
"""Convert the value into a list. If it was a string the returned list
|
| 1362 |
+
will be a list of characters.
|
| 1363 |
+
"""
|
| 1364 |
+
return list(value)
|
| 1365 |
+
|
| 1366 |
+
|
| 1367 |
+
@async_variant(sync_do_list) # type: ignore
|
| 1368 |
+
async def do_list(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]") -> "t.List[V]":
|
| 1369 |
+
return await auto_to_list(value)
|
| 1370 |
+
|
| 1371 |
+
|
| 1372 |
+
def do_mark_safe(value: str) -> Markup:
|
| 1373 |
+
"""Mark the value as safe which means that in an environment with automatic
|
| 1374 |
+
escaping enabled this variable will not be escaped.
|
| 1375 |
+
"""
|
| 1376 |
+
return Markup(value)
|
| 1377 |
+
|
| 1378 |
+
|
| 1379 |
+
def do_mark_unsafe(value: str) -> str:
|
| 1380 |
+
"""Mark a value as unsafe. This is the reverse operation for :func:`safe`."""
|
| 1381 |
+
return str(value)
|
| 1382 |
+
|
| 1383 |
+
|
| 1384 |
+
@typing.overload
|
| 1385 |
+
def do_reverse(value: str) -> str: ...
|
| 1386 |
+
|
| 1387 |
+
|
| 1388 |
+
@typing.overload
|
| 1389 |
+
def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]": ...
|
| 1390 |
+
|
| 1391 |
+
|
| 1392 |
+
def do_reverse(value: t.Union[str, t.Iterable[V]]) -> t.Union[str, t.Iterable[V]]:
|
| 1393 |
+
"""Reverse the object or return an iterator that iterates over it the other
|
| 1394 |
+
way round.
|
| 1395 |
+
"""
|
| 1396 |
+
if isinstance(value, str):
|
| 1397 |
+
return value[::-1]
|
| 1398 |
+
|
| 1399 |
+
try:
|
| 1400 |
+
return reversed(value) # type: ignore
|
| 1401 |
+
except TypeError:
|
| 1402 |
+
try:
|
| 1403 |
+
rv = list(value)
|
| 1404 |
+
rv.reverse()
|
| 1405 |
+
return rv
|
| 1406 |
+
except TypeError as e:
|
| 1407 |
+
raise FilterArgumentError("argument must be iterable") from e
|
| 1408 |
+
|
| 1409 |
+
|
| 1410 |
+
@pass_environment
|
| 1411 |
+
def do_attr(
|
| 1412 |
+
environment: "Environment", obj: t.Any, name: str
|
| 1413 |
+
) -> t.Union[Undefined, t.Any]:
|
| 1414 |
+
"""Get an attribute of an object. ``foo|attr("bar")`` works like
|
| 1415 |
+
``foo.bar`` just that always an attribute is returned and items are not
|
| 1416 |
+
looked up.
|
| 1417 |
+
|
| 1418 |
+
See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
|
| 1419 |
+
"""
|
| 1420 |
+
try:
|
| 1421 |
+
name = str(name)
|
| 1422 |
+
except UnicodeError:
|
| 1423 |
+
pass
|
| 1424 |
+
else:
|
| 1425 |
+
try:
|
| 1426 |
+
value = getattr(obj, name)
|
| 1427 |
+
except AttributeError:
|
| 1428 |
+
pass
|
| 1429 |
+
else:
|
| 1430 |
+
if environment.sandboxed:
|
| 1431 |
+
environment = t.cast("SandboxedEnvironment", environment)
|
| 1432 |
+
|
| 1433 |
+
if not environment.is_safe_attribute(obj, name, value):
|
| 1434 |
+
return environment.unsafe_undefined(obj, name)
|
| 1435 |
+
|
| 1436 |
+
return value
|
| 1437 |
+
|
| 1438 |
+
return environment.undefined(obj=obj, name=name)
|
| 1439 |
+
|
| 1440 |
+
|
| 1441 |
+
@typing.overload
|
| 1442 |
+
def sync_do_map(
|
| 1443 |
+
context: "Context",
|
| 1444 |
+
value: t.Iterable[t.Any],
|
| 1445 |
+
name: str,
|
| 1446 |
+
*args: t.Any,
|
| 1447 |
+
**kwargs: t.Any,
|
| 1448 |
+
) -> t.Iterable[t.Any]: ...
|
| 1449 |
+
|
| 1450 |
+
|
| 1451 |
+
@typing.overload
|
| 1452 |
+
def sync_do_map(
|
| 1453 |
+
context: "Context",
|
| 1454 |
+
value: t.Iterable[t.Any],
|
| 1455 |
+
*,
|
| 1456 |
+
attribute: str = ...,
|
| 1457 |
+
default: t.Optional[t.Any] = None,
|
| 1458 |
+
) -> t.Iterable[t.Any]: ...
|
| 1459 |
+
|
| 1460 |
+
|
| 1461 |
+
@pass_context
|
| 1462 |
+
def sync_do_map(
|
| 1463 |
+
context: "Context", value: t.Iterable[t.Any], *args: t.Any, **kwargs: t.Any
|
| 1464 |
+
) -> t.Iterable[t.Any]:
|
| 1465 |
+
"""Applies a filter on a sequence of objects or looks up an attribute.
|
| 1466 |
+
This is useful when dealing with lists of objects but you are really
|
| 1467 |
+
only interested in a certain value of it.
|
| 1468 |
+
|
| 1469 |
+
The basic usage is mapping on an attribute. Imagine you have a list
|
| 1470 |
+
of users but you are only interested in a list of usernames:
|
| 1471 |
+
|
| 1472 |
+
.. sourcecode:: jinja
|
| 1473 |
+
|
| 1474 |
+
Users on this page: {{ users|map(attribute='username')|join(', ') }}
|
| 1475 |
+
|
| 1476 |
+
You can specify a ``default`` value to use if an object in the list
|
| 1477 |
+
does not have the given attribute.
|
| 1478 |
+
|
| 1479 |
+
.. sourcecode:: jinja
|
| 1480 |
+
|
| 1481 |
+
{{ users|map(attribute="username", default="Anonymous")|join(", ") }}
|
| 1482 |
+
|
| 1483 |
+
Alternatively you can let it invoke a filter by passing the name of the
|
| 1484 |
+
filter and the arguments afterwards. A good example would be applying a
|
| 1485 |
+
text conversion filter on a sequence:
|
| 1486 |
+
|
| 1487 |
+
.. sourcecode:: jinja
|
| 1488 |
+
|
| 1489 |
+
Users on this page: {{ titles|map('lower')|join(', ') }}
|
| 1490 |
+
|
| 1491 |
+
Similar to a generator comprehension such as:
|
| 1492 |
+
|
| 1493 |
+
.. code-block:: python
|
| 1494 |
+
|
| 1495 |
+
(u.username for u in users)
|
| 1496 |
+
(getattr(u, "username", "Anonymous") for u in users)
|
| 1497 |
+
(do_lower(x) for x in titles)
|
| 1498 |
+
|
| 1499 |
+
.. versionchanged:: 2.11.0
|
| 1500 |
+
Added the ``default`` parameter.
|
| 1501 |
+
|
| 1502 |
+
.. versionadded:: 2.7
|
| 1503 |
+
"""
|
| 1504 |
+
if value:
|
| 1505 |
+
func = prepare_map(context, args, kwargs)
|
| 1506 |
+
|
| 1507 |
+
for item in value:
|
| 1508 |
+
yield func(item)
|
| 1509 |
+
|
| 1510 |
+
|
| 1511 |
+
@typing.overload
|
| 1512 |
+
def do_map(
|
| 1513 |
+
context: "Context",
|
| 1514 |
+
value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],
|
| 1515 |
+
name: str,
|
| 1516 |
+
*args: t.Any,
|
| 1517 |
+
**kwargs: t.Any,
|
| 1518 |
+
) -> t.Iterable[t.Any]: ...
|
| 1519 |
+
|
| 1520 |
+
|
| 1521 |
+
@typing.overload
|
| 1522 |
+
def do_map(
|
| 1523 |
+
context: "Context",
|
| 1524 |
+
value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],
|
| 1525 |
+
*,
|
| 1526 |
+
attribute: str = ...,
|
| 1527 |
+
default: t.Optional[t.Any] = None,
|
| 1528 |
+
) -> t.Iterable[t.Any]: ...
|
| 1529 |
+
|
| 1530 |
+
|
| 1531 |
+
@async_variant(sync_do_map) # type: ignore
|
| 1532 |
+
async def do_map(
|
| 1533 |
+
context: "Context",
|
| 1534 |
+
value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],
|
| 1535 |
+
*args: t.Any,
|
| 1536 |
+
**kwargs: t.Any,
|
| 1537 |
+
) -> t.AsyncIterable[t.Any]:
|
| 1538 |
+
if value:
|
| 1539 |
+
func = prepare_map(context, args, kwargs)
|
| 1540 |
+
|
| 1541 |
+
async for item in auto_aiter(value):
|
| 1542 |
+
yield await auto_await(func(item))
|
| 1543 |
+
|
| 1544 |
+
|
| 1545 |
+
@pass_context
|
| 1546 |
+
def sync_do_select(
|
| 1547 |
+
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
|
| 1548 |
+
) -> "t.Iterator[V]":
|
| 1549 |
+
"""Filters a sequence of objects by applying a test to each object,
|
| 1550 |
+
and only selecting the objects with the test succeeding.
|
| 1551 |
+
|
| 1552 |
+
If no test is specified, each object will be evaluated as a boolean.
|
| 1553 |
+
|
| 1554 |
+
Example usage:
|
| 1555 |
+
|
| 1556 |
+
.. sourcecode:: jinja
|
| 1557 |
+
|
| 1558 |
+
{{ numbers|select("odd") }}
|
| 1559 |
+
{{ numbers|select("odd") }}
|
| 1560 |
+
{{ numbers|select("divisibleby", 3) }}
|
| 1561 |
+
{{ numbers|select("lessthan", 42) }}
|
| 1562 |
+
{{ strings|select("equalto", "mystring") }}
|
| 1563 |
+
|
| 1564 |
+
Similar to a generator comprehension such as:
|
| 1565 |
+
|
| 1566 |
+
.. code-block:: python
|
| 1567 |
+
|
| 1568 |
+
(n for n in numbers if test_odd(n))
|
| 1569 |
+
(n for n in numbers if test_divisibleby(n, 3))
|
| 1570 |
+
|
| 1571 |
+
.. versionadded:: 2.7
|
| 1572 |
+
"""
|
| 1573 |
+
return select_or_reject(context, value, args, kwargs, lambda x: x, False)
|
| 1574 |
+
|
| 1575 |
+
|
| 1576 |
+
@async_variant(sync_do_select) # type: ignore
|
| 1577 |
+
async def do_select(
|
| 1578 |
+
context: "Context",
|
| 1579 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
| 1580 |
+
*args: t.Any,
|
| 1581 |
+
**kwargs: t.Any,
|
| 1582 |
+
) -> "t.AsyncIterator[V]":
|
| 1583 |
+
return async_select_or_reject(context, value, args, kwargs, lambda x: x, False)
|
| 1584 |
+
|
| 1585 |
+
|
| 1586 |
+
@pass_context
|
| 1587 |
+
def sync_do_reject(
|
| 1588 |
+
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
|
| 1589 |
+
) -> "t.Iterator[V]":
|
| 1590 |
+
"""Filters a sequence of objects by applying a test to each object,
|
| 1591 |
+
and rejecting the objects with the test succeeding.
|
| 1592 |
+
|
| 1593 |
+
If no test is specified, each object will be evaluated as a boolean.
|
| 1594 |
+
|
| 1595 |
+
Example usage:
|
| 1596 |
+
|
| 1597 |
+
.. sourcecode:: jinja
|
| 1598 |
+
|
| 1599 |
+
{{ numbers|reject("odd") }}
|
| 1600 |
+
|
| 1601 |
+
Similar to a generator comprehension such as:
|
| 1602 |
+
|
| 1603 |
+
.. code-block:: python
|
| 1604 |
+
|
| 1605 |
+
(n for n in numbers if not test_odd(n))
|
| 1606 |
+
|
| 1607 |
+
.. versionadded:: 2.7
|
| 1608 |
+
"""
|
| 1609 |
+
return select_or_reject(context, value, args, kwargs, lambda x: not x, False)
|
| 1610 |
+
|
| 1611 |
+
|
| 1612 |
+
@async_variant(sync_do_reject) # type: ignore
|
| 1613 |
+
async def do_reject(
|
| 1614 |
+
context: "Context",
|
| 1615 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
| 1616 |
+
*args: t.Any,
|
| 1617 |
+
**kwargs: t.Any,
|
| 1618 |
+
) -> "t.AsyncIterator[V]":
|
| 1619 |
+
return async_select_or_reject(context, value, args, kwargs, lambda x: not x, False)
|
| 1620 |
+
|
| 1621 |
+
|
| 1622 |
+
@pass_context
|
| 1623 |
+
def sync_do_selectattr(
|
| 1624 |
+
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
|
| 1625 |
+
) -> "t.Iterator[V]":
|
| 1626 |
+
"""Filters a sequence of objects by applying a test to the specified
|
| 1627 |
+
attribute of each object, and only selecting the objects with the
|
| 1628 |
+
test succeeding.
|
| 1629 |
+
|
| 1630 |
+
If no test is specified, the attribute's value will be evaluated as
|
| 1631 |
+
a boolean.
|
| 1632 |
+
|
| 1633 |
+
Example usage:
|
| 1634 |
+
|
| 1635 |
+
.. sourcecode:: jinja
|
| 1636 |
+
|
| 1637 |
+
{{ users|selectattr("is_active") }}
|
| 1638 |
+
{{ users|selectattr("email", "none") }}
|
| 1639 |
+
|
| 1640 |
+
Similar to a generator comprehension such as:
|
| 1641 |
+
|
| 1642 |
+
.. code-block:: python
|
| 1643 |
+
|
| 1644 |
+
(user for user in users if user.is_active)
|
| 1645 |
+
(user for user in users if test_none(user.email))
|
| 1646 |
+
|
| 1647 |
+
.. versionadded:: 2.7
|
| 1648 |
+
"""
|
| 1649 |
+
return select_or_reject(context, value, args, kwargs, lambda x: x, True)
|
| 1650 |
+
|
| 1651 |
+
|
| 1652 |
+
@async_variant(sync_do_selectattr) # type: ignore
|
| 1653 |
+
async def do_selectattr(
|
| 1654 |
+
context: "Context",
|
| 1655 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
| 1656 |
+
*args: t.Any,
|
| 1657 |
+
**kwargs: t.Any,
|
| 1658 |
+
) -> "t.AsyncIterator[V]":
|
| 1659 |
+
return async_select_or_reject(context, value, args, kwargs, lambda x: x, True)
|
| 1660 |
+
|
| 1661 |
+
|
| 1662 |
+
@pass_context
|
| 1663 |
+
def sync_do_rejectattr(
|
| 1664 |
+
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
|
| 1665 |
+
) -> "t.Iterator[V]":
|
| 1666 |
+
"""Filters a sequence of objects by applying a test to the specified
|
| 1667 |
+
attribute of each object, and rejecting the objects with the test
|
| 1668 |
+
succeeding.
|
| 1669 |
+
|
| 1670 |
+
If no test is specified, the attribute's value will be evaluated as
|
| 1671 |
+
a boolean.
|
| 1672 |
+
|
| 1673 |
+
.. sourcecode:: jinja
|
| 1674 |
+
|
| 1675 |
+
{{ users|rejectattr("is_active") }}
|
| 1676 |
+
{{ users|rejectattr("email", "none") }}
|
| 1677 |
+
|
| 1678 |
+
Similar to a generator comprehension such as:
|
| 1679 |
+
|
| 1680 |
+
.. code-block:: python
|
| 1681 |
+
|
| 1682 |
+
(user for user in users if not user.is_active)
|
| 1683 |
+
(user for user in users if not test_none(user.email))
|
| 1684 |
+
|
| 1685 |
+
.. versionadded:: 2.7
|
| 1686 |
+
"""
|
| 1687 |
+
return select_or_reject(context, value, args, kwargs, lambda x: not x, True)
|
| 1688 |
+
|
| 1689 |
+
|
| 1690 |
+
@async_variant(sync_do_rejectattr) # type: ignore
|
| 1691 |
+
async def do_rejectattr(
|
| 1692 |
+
context: "Context",
|
| 1693 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
| 1694 |
+
*args: t.Any,
|
| 1695 |
+
**kwargs: t.Any,
|
| 1696 |
+
) -> "t.AsyncIterator[V]":
|
| 1697 |
+
return async_select_or_reject(context, value, args, kwargs, lambda x: not x, True)
|
| 1698 |
+
|
| 1699 |
+
|
| 1700 |
+
@pass_eval_context
|
| 1701 |
+
def do_tojson(
|
| 1702 |
+
eval_ctx: "EvalContext", value: t.Any, indent: t.Optional[int] = None
|
| 1703 |
+
) -> Markup:
|
| 1704 |
+
"""Serialize an object to a string of JSON, and mark it safe to
|
| 1705 |
+
render in HTML. This filter is only for use in HTML documents.
|
| 1706 |
+
|
| 1707 |
+
The returned string is safe to render in HTML documents and
|
| 1708 |
+
``<script>`` tags. The exception is in HTML attributes that are
|
| 1709 |
+
double quoted; either use single quotes or the ``|forceescape``
|
| 1710 |
+
filter.
|
| 1711 |
+
|
| 1712 |
+
:param value: The object to serialize to JSON.
|
| 1713 |
+
:param indent: The ``indent`` parameter passed to ``dumps``, for
|
| 1714 |
+
pretty-printing the value.
|
| 1715 |
+
|
| 1716 |
+
.. versionadded:: 2.9
|
| 1717 |
+
"""
|
| 1718 |
+
policies = eval_ctx.environment.policies
|
| 1719 |
+
dumps = policies["json.dumps_function"]
|
| 1720 |
+
kwargs = policies["json.dumps_kwargs"]
|
| 1721 |
+
|
| 1722 |
+
if indent is not None:
|
| 1723 |
+
kwargs = kwargs.copy()
|
| 1724 |
+
kwargs["indent"] = indent
|
| 1725 |
+
|
| 1726 |
+
return htmlsafe_json_dumps(value, dumps=dumps, **kwargs)
|
| 1727 |
+
|
| 1728 |
+
|
| 1729 |
+
def prepare_map(
|
| 1730 |
+
context: "Context", args: t.Tuple[t.Any, ...], kwargs: t.Dict[str, t.Any]
|
| 1731 |
+
) -> t.Callable[[t.Any], t.Any]:
|
| 1732 |
+
if not args and "attribute" in kwargs:
|
| 1733 |
+
attribute = kwargs.pop("attribute")
|
| 1734 |
+
default = kwargs.pop("default", None)
|
| 1735 |
+
|
| 1736 |
+
if kwargs:
|
| 1737 |
+
raise FilterArgumentError(
|
| 1738 |
+
f"Unexpected keyword argument {next(iter(kwargs))!r}"
|
| 1739 |
+
)
|
| 1740 |
+
|
| 1741 |
+
func = make_attrgetter(context.environment, attribute, default=default)
|
| 1742 |
+
else:
|
| 1743 |
+
try:
|
| 1744 |
+
name = args[0]
|
| 1745 |
+
args = args[1:]
|
| 1746 |
+
except LookupError:
|
| 1747 |
+
raise FilterArgumentError("map requires a filter argument") from None
|
| 1748 |
+
|
| 1749 |
+
def func(item: t.Any) -> t.Any:
|
| 1750 |
+
return context.environment.call_filter(
|
| 1751 |
+
name, item, args, kwargs, context=context
|
| 1752 |
+
)
|
| 1753 |
+
|
| 1754 |
+
return func
|
| 1755 |
+
|
| 1756 |
+
|
| 1757 |
+
def prepare_select_or_reject(
|
| 1758 |
+
context: "Context",
|
| 1759 |
+
args: t.Tuple[t.Any, ...],
|
| 1760 |
+
kwargs: t.Dict[str, t.Any],
|
| 1761 |
+
modfunc: t.Callable[[t.Any], t.Any],
|
| 1762 |
+
lookup_attr: bool,
|
| 1763 |
+
) -> t.Callable[[t.Any], t.Any]:
|
| 1764 |
+
if lookup_attr:
|
| 1765 |
+
try:
|
| 1766 |
+
attr = args[0]
|
| 1767 |
+
except LookupError:
|
| 1768 |
+
raise FilterArgumentError("Missing parameter for attribute name") from None
|
| 1769 |
+
|
| 1770 |
+
transfunc = make_attrgetter(context.environment, attr)
|
| 1771 |
+
off = 1
|
| 1772 |
+
else:
|
| 1773 |
+
off = 0
|
| 1774 |
+
|
| 1775 |
+
def transfunc(x: V) -> V:
|
| 1776 |
+
return x
|
| 1777 |
+
|
| 1778 |
+
try:
|
| 1779 |
+
name = args[off]
|
| 1780 |
+
args = args[1 + off :]
|
| 1781 |
+
|
| 1782 |
+
def func(item: t.Any) -> t.Any:
|
| 1783 |
+
return context.environment.call_test(name, item, args, kwargs, context)
|
| 1784 |
+
|
| 1785 |
+
except LookupError:
|
| 1786 |
+
func = bool # type: ignore
|
| 1787 |
+
|
| 1788 |
+
return lambda item: modfunc(func(transfunc(item)))
|
| 1789 |
+
|
| 1790 |
+
|
| 1791 |
+
def select_or_reject(
|
| 1792 |
+
context: "Context",
|
| 1793 |
+
value: "t.Iterable[V]",
|
| 1794 |
+
args: t.Tuple[t.Any, ...],
|
| 1795 |
+
kwargs: t.Dict[str, t.Any],
|
| 1796 |
+
modfunc: t.Callable[[t.Any], t.Any],
|
| 1797 |
+
lookup_attr: bool,
|
| 1798 |
+
) -> "t.Iterator[V]":
|
| 1799 |
+
if value:
|
| 1800 |
+
func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
|
| 1801 |
+
|
| 1802 |
+
for item in value:
|
| 1803 |
+
if func(item):
|
| 1804 |
+
yield item
|
| 1805 |
+
|
| 1806 |
+
|
| 1807 |
+
async def async_select_or_reject(
|
| 1808 |
+
context: "Context",
|
| 1809 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
| 1810 |
+
args: t.Tuple[t.Any, ...],
|
| 1811 |
+
kwargs: t.Dict[str, t.Any],
|
| 1812 |
+
modfunc: t.Callable[[t.Any], t.Any],
|
| 1813 |
+
lookup_attr: bool,
|
| 1814 |
+
) -> "t.AsyncIterator[V]":
|
| 1815 |
+
if value:
|
| 1816 |
+
func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
|
| 1817 |
+
|
| 1818 |
+
async for item in auto_aiter(value):
|
| 1819 |
+
if func(item):
|
| 1820 |
+
yield item
|
| 1821 |
+
|
| 1822 |
+
|
| 1823 |
+
FILTERS = {
|
| 1824 |
+
"abs": abs,
|
| 1825 |
+
"attr": do_attr,
|
| 1826 |
+
"batch": do_batch,
|
| 1827 |
+
"capitalize": do_capitalize,
|
| 1828 |
+
"center": do_center,
|
| 1829 |
+
"count": len,
|
| 1830 |
+
"d": do_default,
|
| 1831 |
+
"default": do_default,
|
| 1832 |
+
"dictsort": do_dictsort,
|
| 1833 |
+
"e": escape,
|
| 1834 |
+
"escape": escape,
|
| 1835 |
+
"filesizeformat": do_filesizeformat,
|
| 1836 |
+
"first": do_first,
|
| 1837 |
+
"float": do_float,
|
| 1838 |
+
"forceescape": do_forceescape,
|
| 1839 |
+
"format": do_format,
|
| 1840 |
+
"groupby": do_groupby,
|
| 1841 |
+
"indent": do_indent,
|
| 1842 |
+
"int": do_int,
|
| 1843 |
+
"join": do_join,
|
| 1844 |
+
"last": do_last,
|
| 1845 |
+
"length": len,
|
| 1846 |
+
"list": do_list,
|
| 1847 |
+
"lower": do_lower,
|
| 1848 |
+
"items": do_items,
|
| 1849 |
+
"map": do_map,
|
| 1850 |
+
"min": do_min,
|
| 1851 |
+
"max": do_max,
|
| 1852 |
+
"pprint": do_pprint,
|
| 1853 |
+
"random": do_random,
|
| 1854 |
+
"reject": do_reject,
|
| 1855 |
+
"rejectattr": do_rejectattr,
|
| 1856 |
+
"replace": do_replace,
|
| 1857 |
+
"reverse": do_reverse,
|
| 1858 |
+
"round": do_round,
|
| 1859 |
+
"safe": do_mark_safe,
|
| 1860 |
+
"select": do_select,
|
| 1861 |
+
"selectattr": do_selectattr,
|
| 1862 |
+
"slice": do_slice,
|
| 1863 |
+
"sort": do_sort,
|
| 1864 |
+
"string": soft_str,
|
| 1865 |
+
"striptags": do_striptags,
|
| 1866 |
+
"sum": do_sum,
|
| 1867 |
+
"title": do_title,
|
| 1868 |
+
"trim": do_trim,
|
| 1869 |
+
"truncate": do_truncate,
|
| 1870 |
+
"unique": do_unique,
|
| 1871 |
+
"upper": do_upper,
|
| 1872 |
+
"urlencode": do_urlencode,
|
| 1873 |
+
"urlize": do_url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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""API and implementations for loading templates from different data
|
| 2 |
+
sources.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import importlib.util
|
| 6 |
+
import os
|
| 7 |
+
import posixpath
|
| 8 |
+
import sys
|
| 9 |
+
import typing as t
|
| 10 |
+
import weakref
|
| 11 |
+
import zipimport
|
| 12 |
+
from collections import abc
|
| 13 |
+
from hashlib import sha1
|
| 14 |
+
from importlib import import_module
|
| 15 |
+
from types import ModuleType
|
| 16 |
+
|
| 17 |
+
from .exceptions import TemplateNotFound
|
| 18 |
+
from .utils import internalcode
|
| 19 |
+
|
| 20 |
+
if t.TYPE_CHECKING:
|
| 21 |
+
from .environment import Environment
|
| 22 |
+
from .environment import Template
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def split_template_path(template: str) -> t.List[str]:
|
| 26 |
+
"""Split a path into segments and perform a sanity check. If it detects
|
| 27 |
+
'..' in the path it will raise a `TemplateNotFound` error.
|
| 28 |
+
"""
|
| 29 |
+
pieces = []
|
| 30 |
+
for piece in template.split("/"):
|
| 31 |
+
if (
|
| 32 |
+
os.path.sep in piece
|
| 33 |
+
or (os.path.altsep and os.path.altsep in piece)
|
| 34 |
+
or piece == os.path.pardir
|
| 35 |
+
):
|
| 36 |
+
raise TemplateNotFound(template)
|
| 37 |
+
elif piece and piece != ".":
|
| 38 |
+
pieces.append(piece)
|
| 39 |
+
return pieces
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class BaseLoader:
|
| 43 |
+
"""Baseclass for all loaders. Subclass this and override `get_source` to
|
| 44 |
+
implement a custom loading mechanism. The environment provides a
|
| 45 |
+
`get_template` method that calls the loader's `load` method to get the
|
| 46 |
+
:class:`Template` object.
|
| 47 |
+
|
| 48 |
+
A very basic example for a loader that looks up templates on the file
|
| 49 |
+
system could look like this::
|
| 50 |
+
|
| 51 |
+
from jinja2 import BaseLoader, TemplateNotFound
|
| 52 |
+
from os.path import join, exists, getmtime
|
| 53 |
+
|
| 54 |
+
class MyLoader(BaseLoader):
|
| 55 |
+
|
| 56 |
+
def __init__(self, path):
|
| 57 |
+
self.path = path
|
| 58 |
+
|
| 59 |
+
def get_source(self, environment, template):
|
| 60 |
+
path = join(self.path, template)
|
| 61 |
+
if not exists(path):
|
| 62 |
+
raise TemplateNotFound(template)
|
| 63 |
+
mtime = getmtime(path)
|
| 64 |
+
with open(path) as f:
|
| 65 |
+
source = f.read()
|
| 66 |
+
return source, path, lambda: mtime == getmtime(path)
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
#: if set to `False` it indicates that the loader cannot provide access
|
| 70 |
+
#: to the source of templates.
|
| 71 |
+
#:
|
| 72 |
+
#: .. versionadded:: 2.4
|
| 73 |
+
has_source_access = True
|
| 74 |
+
|
| 75 |
+
def get_source(
|
| 76 |
+
self, environment: "Environment", template: str
|
| 77 |
+
) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
|
| 78 |
+
"""Get the template source, filename and reload helper for a template.
|
| 79 |
+
It's passed the environment and template name and has to return a
|
| 80 |
+
tuple in the form ``(source, filename, uptodate)`` or raise a
|
| 81 |
+
`TemplateNotFound` error if it can't locate the template.
|
| 82 |
+
|
| 83 |
+
The source part of the returned tuple must be the source of the
|
| 84 |
+
template as a string. The filename should be the name of the
|
| 85 |
+
file on the filesystem if it was loaded from there, otherwise
|
| 86 |
+
``None``. The filename is used by Python for the tracebacks
|
| 87 |
+
if no loader extension is used.
|
| 88 |
+
|
| 89 |
+
The last item in the tuple is the `uptodate` function. If auto
|
| 90 |
+
reloading is enabled it's always called to check if the template
|
| 91 |
+
changed. No arguments are passed so the function must store the
|
| 92 |
+
old state somewhere (for example in a closure). If it returns `False`
|
| 93 |
+
the template will be reloaded.
|
| 94 |
+
"""
|
| 95 |
+
if not self.has_source_access:
|
| 96 |
+
raise RuntimeError(
|
| 97 |
+
f"{type(self).__name__} cannot provide access to the source"
|
| 98 |
+
)
|
| 99 |
+
raise TemplateNotFound(template)
|
| 100 |
+
|
| 101 |
+
def list_templates(self) -> t.List[str]:
|
| 102 |
+
"""Iterates over all templates. If the loader does not support that
|
| 103 |
+
it should raise a :exc:`TypeError` which is the default behavior.
|
| 104 |
+
"""
|
| 105 |
+
raise TypeError("this loader cannot iterate over all templates")
|
| 106 |
+
|
| 107 |
+
@internalcode
|
| 108 |
+
def load(
|
| 109 |
+
self,
|
| 110 |
+
environment: "Environment",
|
| 111 |
+
name: str,
|
| 112 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
| 113 |
+
) -> "Template":
|
| 114 |
+
"""Loads a template. This method looks up the template in the cache
|
| 115 |
+
or loads one by calling :meth:`get_source`. Subclasses should not
|
| 116 |
+
override this method as loaders working on collections of other
|
| 117 |
+
loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)
|
| 118 |
+
will not call this method but `get_source` directly.
|
| 119 |
+
"""
|
| 120 |
+
code = None
|
| 121 |
+
if globals is None:
|
| 122 |
+
globals = {}
|
| 123 |
+
|
| 124 |
+
# first we try to get the source for this template together
|
| 125 |
+
# with the filename and the uptodate function.
|
| 126 |
+
source, filename, uptodate = self.get_source(environment, name)
|
| 127 |
+
|
| 128 |
+
# try to load the code from the bytecode cache if there is a
|
| 129 |
+
# bytecode cache configured.
|
| 130 |
+
bcc = environment.bytecode_cache
|
| 131 |
+
if bcc is not None:
|
| 132 |
+
bucket = bcc.get_bucket(environment, name, filename, source)
|
| 133 |
+
code = bucket.code
|
| 134 |
+
|
| 135 |
+
# if we don't have code so far (not cached, no longer up to
|
| 136 |
+
# date) etc. we compile the template
|
| 137 |
+
if code is None:
|
| 138 |
+
code = environment.compile(source, name, filename)
|
| 139 |
+
|
| 140 |
+
# if the bytecode cache is available and the bucket doesn't
|
| 141 |
+
# have a code so far, we give the bucket the new code and put
|
| 142 |
+
# it back to the bytecode cache.
|
| 143 |
+
if bcc is not None and bucket.code is None:
|
| 144 |
+
bucket.code = code
|
| 145 |
+
bcc.set_bucket(bucket)
|
| 146 |
+
|
| 147 |
+
return environment.template_class.from_code(
|
| 148 |
+
environment, code, globals, uptodate
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class FileSystemLoader(BaseLoader):
|
| 153 |
+
"""Load templates from a directory in the file system.
|
| 154 |
+
|
| 155 |
+
The path can be relative or absolute. Relative paths are relative to
|
| 156 |
+
the current working directory.
|
| 157 |
+
|
| 158 |
+
.. code-block:: python
|
| 159 |
+
|
| 160 |
+
loader = FileSystemLoader("templates")
|
| 161 |
+
|
| 162 |
+
A list of paths can be given. The directories will be searched in
|
| 163 |
+
order, stopping at the first matching template.
|
| 164 |
+
|
| 165 |
+
.. code-block:: python
|
| 166 |
+
|
| 167 |
+
loader = FileSystemLoader(["/override/templates", "/default/templates"])
|
| 168 |
+
|
| 169 |
+
:param searchpath: A path, or list of paths, to the directory that
|
| 170 |
+
contains the templates.
|
| 171 |
+
:param encoding: Use this encoding to read the text from template
|
| 172 |
+
files.
|
| 173 |
+
:param followlinks: Follow symbolic links in the path.
|
| 174 |
+
|
| 175 |
+
.. versionchanged:: 2.8
|
| 176 |
+
Added the ``followlinks`` parameter.
|
| 177 |
+
"""
|
| 178 |
+
|
| 179 |
+
def __init__(
|
| 180 |
+
self,
|
| 181 |
+
searchpath: t.Union[
|
| 182 |
+
str, "os.PathLike[str]", t.Sequence[t.Union[str, "os.PathLike[str]"]]
|
| 183 |
+
],
|
| 184 |
+
encoding: str = "utf-8",
|
| 185 |
+
followlinks: bool = False,
|
| 186 |
+
) -> None:
|
| 187 |
+
if not isinstance(searchpath, abc.Iterable) or isinstance(searchpath, str):
|
| 188 |
+
searchpath = [searchpath]
|
| 189 |
+
|
| 190 |
+
self.searchpath = [os.fspath(p) for p in searchpath]
|
| 191 |
+
self.encoding = encoding
|
| 192 |
+
self.followlinks = followlinks
|
| 193 |
+
|
| 194 |
+
def get_source(
|
| 195 |
+
self, environment: "Environment", template: str
|
| 196 |
+
) -> t.Tuple[str, str, t.Callable[[], bool]]:
|
| 197 |
+
pieces = split_template_path(template)
|
| 198 |
+
|
| 199 |
+
for searchpath in self.searchpath:
|
| 200 |
+
# Use posixpath even on Windows to avoid "drive:" or UNC
|
| 201 |
+
# segments breaking out of the search directory.
|
| 202 |
+
filename = posixpath.join(searchpath, *pieces)
|
| 203 |
+
|
| 204 |
+
if os.path.isfile(filename):
|
| 205 |
+
break
|
| 206 |
+
else:
|
| 207 |
+
plural = "path" if len(self.searchpath) == 1 else "paths"
|
| 208 |
+
paths_str = ", ".join(repr(p) for p in self.searchpath)
|
| 209 |
+
raise TemplateNotFound(
|
| 210 |
+
template,
|
| 211 |
+
f"{template!r} not found in search {plural}: {paths_str}",
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
with open(filename, encoding=self.encoding) as f:
|
| 215 |
+
contents = f.read()
|
| 216 |
+
|
| 217 |
+
mtime = os.path.getmtime(filename)
|
| 218 |
+
|
| 219 |
+
def uptodate() -> bool:
|
| 220 |
+
try:
|
| 221 |
+
return os.path.getmtime(filename) == mtime
|
| 222 |
+
except OSError:
|
| 223 |
+
return False
|
| 224 |
+
|
| 225 |
+
# Use normpath to convert Windows altsep to sep.
|
| 226 |
+
return contents, os.path.normpath(filename), uptodate
|
| 227 |
+
|
| 228 |
+
def list_templates(self) -> t.List[str]:
|
| 229 |
+
found = set()
|
| 230 |
+
for searchpath in self.searchpath:
|
| 231 |
+
walk_dir = os.walk(searchpath, followlinks=self.followlinks)
|
| 232 |
+
for dirpath, _, filenames in walk_dir:
|
| 233 |
+
for filename in filenames:
|
| 234 |
+
template = (
|
| 235 |
+
os.path.join(dirpath, filename)[len(searchpath) :]
|
| 236 |
+
.strip(os.path.sep)
|
| 237 |
+
.replace(os.path.sep, "/")
|
| 238 |
+
)
|
| 239 |
+
if template[:2] == "./":
|
| 240 |
+
template = template[2:]
|
| 241 |
+
if template not in found:
|
| 242 |
+
found.add(template)
|
| 243 |
+
return sorted(found)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
if sys.version_info >= (3, 13):
|
| 247 |
+
|
| 248 |
+
def _get_zipimporter_files(z: t.Any) -> t.Dict[str, object]:
|
| 249 |
+
try:
|
| 250 |
+
get_files = z._get_files
|
| 251 |
+
except AttributeError as e:
|
| 252 |
+
raise TypeError(
|
| 253 |
+
"This zip import does not have the required"
|
| 254 |
+
" metadata to list templates."
|
| 255 |
+
) from e
|
| 256 |
+
return get_files()
|
| 257 |
+
else:
|
| 258 |
+
|
| 259 |
+
def _get_zipimporter_files(z: t.Any) -> t.Dict[str, object]:
|
| 260 |
+
try:
|
| 261 |
+
files = z._files
|
| 262 |
+
except AttributeError as e:
|
| 263 |
+
raise TypeError(
|
| 264 |
+
"This zip import does not have the required"
|
| 265 |
+
" metadata to list templates."
|
| 266 |
+
) from e
|
| 267 |
+
return files # type: ignore[no-any-return]
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
class PackageLoader(BaseLoader):
|
| 271 |
+
"""Load templates from a directory in a Python package.
|
| 272 |
+
|
| 273 |
+
:param package_name: Import name of the package that contains the
|
| 274 |
+
template directory.
|
| 275 |
+
:param package_path: Directory within the imported package that
|
| 276 |
+
contains the templates.
|
| 277 |
+
:param encoding: Encoding of template files.
|
| 278 |
+
|
| 279 |
+
The following example looks up templates in the ``pages`` directory
|
| 280 |
+
within the ``project.ui`` package.
|
| 281 |
+
|
| 282 |
+
.. code-block:: python
|
| 283 |
+
|
| 284 |
+
loader = PackageLoader("project.ui", "pages")
|
| 285 |
+
|
| 286 |
+
Only packages installed as directories (standard pip behavior) or
|
| 287 |
+
zip/egg files (less common) are supported. The Python API for
|
| 288 |
+
introspecting data in packages is too limited to support other
|
| 289 |
+
installation methods the way this loader requires.
|
| 290 |
+
|
| 291 |
+
There is limited support for :pep:`420` namespace packages. The
|
| 292 |
+
template directory is assumed to only be in one namespace
|
| 293 |
+
contributor. Zip files contributing to a namespace are not
|
| 294 |
+
supported.
|
| 295 |
+
|
| 296 |
+
.. versionchanged:: 3.0
|
| 297 |
+
No longer uses ``setuptools`` as a dependency.
|
| 298 |
+
|
| 299 |
+
.. versionchanged:: 3.0
|
| 300 |
+
Limited PEP 420 namespace package support.
|
| 301 |
+
"""
|
| 302 |
+
|
| 303 |
+
def __init__(
|
| 304 |
+
self,
|
| 305 |
+
package_name: str,
|
| 306 |
+
package_path: "str" = "templates",
|
| 307 |
+
encoding: str = "utf-8",
|
| 308 |
+
) -> None:
|
| 309 |
+
package_path = os.path.normpath(package_path).rstrip(os.path.sep)
|
| 310 |
+
|
| 311 |
+
# normpath preserves ".", which isn't valid in zip paths.
|
| 312 |
+
if package_path == os.path.curdir:
|
| 313 |
+
package_path = ""
|
| 314 |
+
elif package_path[:2] == os.path.curdir + os.path.sep:
|
| 315 |
+
package_path = package_path[2:]
|
| 316 |
+
|
| 317 |
+
self.package_path = package_path
|
| 318 |
+
self.package_name = package_name
|
| 319 |
+
self.encoding = encoding
|
| 320 |
+
|
| 321 |
+
# Make sure the package exists. This also makes namespace
|
| 322 |
+
# packages work, otherwise get_loader returns None.
|
| 323 |
+
import_module(package_name)
|
| 324 |
+
spec = importlib.util.find_spec(package_name)
|
| 325 |
+
assert spec is not None, "An import spec was not found for the package."
|
| 326 |
+
loader = spec.loader
|
| 327 |
+
assert loader is not None, "A loader was not found for the package."
|
| 328 |
+
self._loader = loader
|
| 329 |
+
self._archive = None
|
| 330 |
+
|
| 331 |
+
if isinstance(loader, zipimport.zipimporter):
|
| 332 |
+
self._archive = loader.archive
|
| 333 |
+
pkgdir = next(iter(spec.submodule_search_locations)) # type: ignore
|
| 334 |
+
template_root = os.path.join(pkgdir, package_path).rstrip(os.path.sep)
|
| 335 |
+
else:
|
| 336 |
+
roots: t.List[str] = []
|
| 337 |
+
|
| 338 |
+
# One element for regular packages, multiple for namespace
|
| 339 |
+
# packages, or None for single module file.
|
| 340 |
+
if spec.submodule_search_locations:
|
| 341 |
+
roots.extend(spec.submodule_search_locations)
|
| 342 |
+
# A single module file, use the parent directory instead.
|
| 343 |
+
elif spec.origin is not None:
|
| 344 |
+
roots.append(os.path.dirname(spec.origin))
|
| 345 |
+
|
| 346 |
+
if not roots:
|
| 347 |
+
raise ValueError(
|
| 348 |
+
f"The {package_name!r} package was not installed in a"
|
| 349 |
+
" way that PackageLoader understands."
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
for root in roots:
|
| 353 |
+
root = os.path.join(root, package_path)
|
| 354 |
+
|
| 355 |
+
if os.path.isdir(root):
|
| 356 |
+
template_root = root
|
| 357 |
+
break
|
| 358 |
+
else:
|
| 359 |
+
raise ValueError(
|
| 360 |
+
f"PackageLoader could not find a {package_path!r} directory"
|
| 361 |
+
f" in the {package_name!r} package."
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
self._template_root = template_root
|
| 365 |
+
|
| 366 |
+
def get_source(
|
| 367 |
+
self, environment: "Environment", template: str
|
| 368 |
+
) -> t.Tuple[str, str, t.Optional[t.Callable[[], bool]]]:
|
| 369 |
+
# Use posixpath even on Windows to avoid "drive:" or UNC
|
| 370 |
+
# segments breaking out of the search directory. Use normpath to
|
| 371 |
+
# convert Windows altsep to sep.
|
| 372 |
+
p = os.path.normpath(
|
| 373 |
+
posixpath.join(self._template_root, *split_template_path(template))
|
| 374 |
+
)
|
| 375 |
+
up_to_date: t.Optional[t.Callable[[], bool]]
|
| 376 |
+
|
| 377 |
+
if self._archive is None:
|
| 378 |
+
# Package is a directory.
|
| 379 |
+
if not os.path.isfile(p):
|
| 380 |
+
raise TemplateNotFound(template)
|
| 381 |
+
|
| 382 |
+
with open(p, "rb") as f:
|
| 383 |
+
source = f.read()
|
| 384 |
+
|
| 385 |
+
mtime = os.path.getmtime(p)
|
| 386 |
+
|
| 387 |
+
def up_to_date() -> bool:
|
| 388 |
+
return os.path.isfile(p) and os.path.getmtime(p) == mtime
|
| 389 |
+
|
| 390 |
+
else:
|
| 391 |
+
# Package is a zip file.
|
| 392 |
+
try:
|
| 393 |
+
source = self._loader.get_data(p) # type: ignore
|
| 394 |
+
except OSError as e:
|
| 395 |
+
raise TemplateNotFound(template) from e
|
| 396 |
+
|
| 397 |
+
# Could use the zip's mtime for all template mtimes, but
|
| 398 |
+
# would need to safely reload the module if it's out of
|
| 399 |
+
# date, so just report it as always current.
|
| 400 |
+
up_to_date = None
|
| 401 |
+
|
| 402 |
+
return source.decode(self.encoding), p, up_to_date
|
| 403 |
+
|
| 404 |
+
def list_templates(self) -> t.List[str]:
|
| 405 |
+
results: t.List[str] = []
|
| 406 |
+
|
| 407 |
+
if self._archive is None:
|
| 408 |
+
# Package is a directory.
|
| 409 |
+
offset = len(self._template_root)
|
| 410 |
+
|
| 411 |
+
for dirpath, _, filenames in os.walk(self._template_root):
|
| 412 |
+
dirpath = dirpath[offset:].lstrip(os.path.sep)
|
| 413 |
+
results.extend(
|
| 414 |
+
os.path.join(dirpath, name).replace(os.path.sep, "/")
|
| 415 |
+
for name in filenames
|
| 416 |
+
)
|
| 417 |
+
else:
|
| 418 |
+
files = _get_zipimporter_files(self._loader)
|
| 419 |
+
|
| 420 |
+
# Package is a zip file.
|
| 421 |
+
prefix = (
|
| 422 |
+
self._template_root[len(self._archive) :].lstrip(os.path.sep)
|
| 423 |
+
+ os.path.sep
|
| 424 |
+
)
|
| 425 |
+
offset = len(prefix)
|
| 426 |
+
|
| 427 |
+
for name in files:
|
| 428 |
+
# Find names under the templates directory that aren't directories.
|
| 429 |
+
if name.startswith(prefix) and name[-1] != os.path.sep:
|
| 430 |
+
results.append(name[offset:].replace(os.path.sep, "/"))
|
| 431 |
+
|
| 432 |
+
results.sort()
|
| 433 |
+
return results
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
class DictLoader(BaseLoader):
|
| 437 |
+
"""Loads a template from a Python dict mapping template names to
|
| 438 |
+
template source. This loader is useful for unittesting:
|
| 439 |
+
|
| 440 |
+
>>> loader = DictLoader({'index.html': 'source here'})
|
| 441 |
+
|
| 442 |
+
Because auto reloading is rarely useful this is disabled by default.
|
| 443 |
+
"""
|
| 444 |
+
|
| 445 |
+
def __init__(self, mapping: t.Mapping[str, str]) -> None:
|
| 446 |
+
self.mapping = mapping
|
| 447 |
+
|
| 448 |
+
def get_source(
|
| 449 |
+
self, environment: "Environment", template: str
|
| 450 |
+
) -> t.Tuple[str, None, t.Callable[[], bool]]:
|
| 451 |
+
if template in self.mapping:
|
| 452 |
+
source = self.mapping[template]
|
| 453 |
+
return source, None, lambda: source == self.mapping.get(template)
|
| 454 |
+
raise TemplateNotFound(template)
|
| 455 |
+
|
| 456 |
+
def list_templates(self) -> t.List[str]:
|
| 457 |
+
return sorted(self.mapping)
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
class FunctionLoader(BaseLoader):
|
| 461 |
+
"""A loader that is passed a function which does the loading. The
|
| 462 |
+
function receives the name of the template and has to return either
|
| 463 |
+
a string with the template source, a tuple in the form ``(source,
|
| 464 |
+
filename, uptodatefunc)`` or `None` if the template does not exist.
|
| 465 |
+
|
| 466 |
+
>>> def load_template(name):
|
| 467 |
+
... if name == 'index.html':
|
| 468 |
+
... return '...'
|
| 469 |
+
...
|
| 470 |
+
>>> loader = FunctionLoader(load_template)
|
| 471 |
+
|
| 472 |
+
The `uptodatefunc` is a function that is called if autoreload is enabled
|
| 473 |
+
and has to return `True` if the template is still up to date. For more
|
| 474 |
+
details have a look at :meth:`BaseLoader.get_source` which has the same
|
| 475 |
+
return value.
|
| 476 |
+
"""
|
| 477 |
+
|
| 478 |
+
def __init__(
|
| 479 |
+
self,
|
| 480 |
+
load_func: t.Callable[
|
| 481 |
+
[str],
|
| 482 |
+
t.Optional[
|
| 483 |
+
t.Union[
|
| 484 |
+
str, t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]
|
| 485 |
+
]
|
| 486 |
+
],
|
| 487 |
+
],
|
| 488 |
+
) -> None:
|
| 489 |
+
self.load_func = load_func
|
| 490 |
+
|
| 491 |
+
def get_source(
|
| 492 |
+
self, environment: "Environment", template: str
|
| 493 |
+
) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
|
| 494 |
+
rv = self.load_func(template)
|
| 495 |
+
|
| 496 |
+
if rv is None:
|
| 497 |
+
raise TemplateNotFound(template)
|
| 498 |
+
|
| 499 |
+
if isinstance(rv, str):
|
| 500 |
+
return rv, None, None
|
| 501 |
+
|
| 502 |
+
return rv
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
class PrefixLoader(BaseLoader):
|
| 506 |
+
"""A loader that is passed a dict of loaders where each loader is bound
|
| 507 |
+
to a prefix. The prefix is delimited from the template by a slash per
|
| 508 |
+
default, which can be changed by setting the `delimiter` argument to
|
| 509 |
+
something else::
|
| 510 |
+
|
| 511 |
+
loader = PrefixLoader({
|
| 512 |
+
'app1': PackageLoader('mypackage.app1'),
|
| 513 |
+
'app2': PackageLoader('mypackage.app2')
|
| 514 |
+
})
|
| 515 |
+
|
| 516 |
+
By loading ``'app1/index.html'`` the file from the app1 package is loaded,
|
| 517 |
+
by loading ``'app2/index.html'`` the file from the second.
|
| 518 |
+
"""
|
| 519 |
+
|
| 520 |
+
def __init__(
|
| 521 |
+
self, mapping: t.Mapping[str, BaseLoader], delimiter: str = "/"
|
| 522 |
+
) -> None:
|
| 523 |
+
self.mapping = mapping
|
| 524 |
+
self.delimiter = delimiter
|
| 525 |
+
|
| 526 |
+
def get_loader(self, template: str) -> t.Tuple[BaseLoader, str]:
|
| 527 |
+
try:
|
| 528 |
+
prefix, name = template.split(self.delimiter, 1)
|
| 529 |
+
loader = self.mapping[prefix]
|
| 530 |
+
except (ValueError, KeyError) as e:
|
| 531 |
+
raise TemplateNotFound(template) from e
|
| 532 |
+
return loader, name
|
| 533 |
+
|
| 534 |
+
def get_source(
|
| 535 |
+
self, environment: "Environment", template: str
|
| 536 |
+
) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
|
| 537 |
+
loader, name = self.get_loader(template)
|
| 538 |
+
try:
|
| 539 |
+
return loader.get_source(environment, name)
|
| 540 |
+
except TemplateNotFound as e:
|
| 541 |
+
# re-raise the exception with the correct filename here.
|
| 542 |
+
# (the one that includes the prefix)
|
| 543 |
+
raise TemplateNotFound(template) from e
|
| 544 |
+
|
| 545 |
+
@internalcode
|
| 546 |
+
def load(
|
| 547 |
+
self,
|
| 548 |
+
environment: "Environment",
|
| 549 |
+
name: str,
|
| 550 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
| 551 |
+
) -> "Template":
|
| 552 |
+
loader, local_name = self.get_loader(name)
|
| 553 |
+
try:
|
| 554 |
+
return loader.load(environment, local_name, globals)
|
| 555 |
+
except TemplateNotFound as e:
|
| 556 |
+
# re-raise the exception with the correct filename here.
|
| 557 |
+
# (the one that includes the prefix)
|
| 558 |
+
raise TemplateNotFound(name) from e
|
| 559 |
+
|
| 560 |
+
def list_templates(self) -> t.List[str]:
|
| 561 |
+
result = []
|
| 562 |
+
for prefix, loader in self.mapping.items():
|
| 563 |
+
for template in loader.list_templates():
|
| 564 |
+
result.append(prefix + self.delimiter + template)
|
| 565 |
+
return result
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
class ChoiceLoader(BaseLoader):
|
| 569 |
+
"""This loader works like the `PrefixLoader` just that no prefix is
|
| 570 |
+
specified. If a template could not be found by one loader the next one
|
| 571 |
+
is tried.
|
| 572 |
+
|
| 573 |
+
>>> loader = ChoiceLoader([
|
| 574 |
+
... FileSystemLoader('/path/to/user/templates'),
|
| 575 |
+
... FileSystemLoader('/path/to/system/templates')
|
| 576 |
+
... ])
|
| 577 |
+
|
| 578 |
+
This is useful if you want to allow users to override builtin templates
|
| 579 |
+
from a different location.
|
| 580 |
+
"""
|
| 581 |
+
|
| 582 |
+
def __init__(self, loaders: t.Sequence[BaseLoader]) -> None:
|
| 583 |
+
self.loaders = loaders
|
| 584 |
+
|
| 585 |
+
def get_source(
|
| 586 |
+
self, environment: "Environment", template: str
|
| 587 |
+
) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
|
| 588 |
+
for loader in self.loaders:
|
| 589 |
+
try:
|
| 590 |
+
return loader.get_source(environment, template)
|
| 591 |
+
except TemplateNotFound:
|
| 592 |
+
pass
|
| 593 |
+
raise TemplateNotFound(template)
|
| 594 |
+
|
| 595 |
+
@internalcode
|
| 596 |
+
def load(
|
| 597 |
+
self,
|
| 598 |
+
environment: "Environment",
|
| 599 |
+
name: str,
|
| 600 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
| 601 |
+
) -> "Template":
|
| 602 |
+
for loader in self.loaders:
|
| 603 |
+
try:
|
| 604 |
+
return loader.load(environment, name, globals)
|
| 605 |
+
except TemplateNotFound:
|
| 606 |
+
pass
|
| 607 |
+
raise TemplateNotFound(name)
|
| 608 |
+
|
| 609 |
+
def list_templates(self) -> t.List[str]:
|
| 610 |
+
found = set()
|
| 611 |
+
for loader in self.loaders:
|
| 612 |
+
found.update(loader.list_templates())
|
| 613 |
+
return sorted(found)
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
class _TemplateModule(ModuleType):
|
| 617 |
+
"""Like a normal module but with support for weak references"""
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
class ModuleLoader(BaseLoader):
|
| 621 |
+
"""This loader loads templates from precompiled templates.
|
| 622 |
+
|
| 623 |
+
Example usage:
|
| 624 |
+
|
| 625 |
+
>>> loader = ModuleLoader('/path/to/compiled/templates')
|
| 626 |
+
|
| 627 |
+
Templates can be precompiled with :meth:`Environment.compile_templates`.
|
| 628 |
+
"""
|
| 629 |
+
|
| 630 |
+
has_source_access = False
|
| 631 |
+
|
| 632 |
+
def __init__(
|
| 633 |
+
self,
|
| 634 |
+
path: t.Union[
|
| 635 |
+
str, "os.PathLike[str]", t.Sequence[t.Union[str, "os.PathLike[str]"]]
|
| 636 |
+
],
|
| 637 |
+
) -> None:
|
| 638 |
+
package_name = f"_jinja2_module_templates_{id(self):x}"
|
| 639 |
+
|
| 640 |
+
# create a fake module that looks for the templates in the
|
| 641 |
+
# path given.
|
| 642 |
+
mod = _TemplateModule(package_name)
|
| 643 |
+
|
| 644 |
+
if not isinstance(path, abc.Iterable) or isinstance(path, str):
|
| 645 |
+
path = [path]
|
| 646 |
+
|
| 647 |
+
mod.__path__ = [os.fspath(p) for p in path]
|
| 648 |
+
|
| 649 |
+
sys.modules[package_name] = weakref.proxy(
|
| 650 |
+
mod, lambda x: sys.modules.pop(package_name, None)
|
| 651 |
+
)
|
| 652 |
+
|
| 653 |
+
# the only strong reference, the sys.modules entry is weak
|
| 654 |
+
# so that the garbage collector can remove it once the
|
| 655 |
+
# loader that created it goes out of business.
|
| 656 |
+
self.module = mod
|
| 657 |
+
self.package_name = package_name
|
| 658 |
+
|
| 659 |
+
@staticmethod
|
| 660 |
+
def get_template_key(name: str) -> str:
|
| 661 |
+
return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()
|
| 662 |
+
|
| 663 |
+
@staticmethod
|
| 664 |
+
def get_module_filename(name: str) -> str:
|
| 665 |
+
return ModuleLoader.get_template_key(name) + ".py"
|
| 666 |
+
|
| 667 |
+
@internalcode
|
| 668 |
+
def load(
|
| 669 |
+
self,
|
| 670 |
+
environment: "Environment",
|
| 671 |
+
name: str,
|
| 672 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
| 673 |
+
) -> "Template":
|
| 674 |
+
key = self.get_template_key(name)
|
| 675 |
+
module = f"{self.package_name}.{key}"
|
| 676 |
+
mod = getattr(self.module, module, None)
|
| 677 |
+
|
| 678 |
+
if mod is None:
|
| 679 |
+
try:
|
| 680 |
+
mod = __import__(module, None, None, ["root"])
|
| 681 |
+
except ImportError as e:
|
| 682 |
+
raise TemplateNotFound(name) from e
|
| 683 |
+
|
| 684 |
+
# remove the entry from sys.modules, we only want the attribute
|
| 685 |
+
# on the module object we have stored on the loader.
|
| 686 |
+
sys.modules.pop(module, None)
|
| 687 |
+
|
| 688 |
+
if globals is None:
|
| 689 |
+
globals = {}
|
| 690 |
+
|
| 691 |
+
return environment.template_class.from_module_dict(
|
| 692 |
+
environment, mod.__dict__, globals
|
| 693 |
+
)
|
janus/lib/python3.10/site-packages/jinja2/sandbox.py
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A sandbox layer that ensures unsafe operations cannot be performed.
|
| 2 |
+
Useful when the template itself comes from an untrusted source.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import operator
|
| 6 |
+
import types
|
| 7 |
+
import typing as t
|
| 8 |
+
from _string import formatter_field_name_split # type: ignore
|
| 9 |
+
from collections import abc
|
| 10 |
+
from collections import deque
|
| 11 |
+
from functools import update_wrapper
|
| 12 |
+
from string import Formatter
|
| 13 |
+
|
| 14 |
+
from markupsafe import EscapeFormatter
|
| 15 |
+
from markupsafe import Markup
|
| 16 |
+
|
| 17 |
+
from .environment import Environment
|
| 18 |
+
from .exceptions import SecurityError
|
| 19 |
+
from .runtime import Context
|
| 20 |
+
from .runtime import Undefined
|
| 21 |
+
|
| 22 |
+
F = t.TypeVar("F", bound=t.Callable[..., t.Any])
|
| 23 |
+
|
| 24 |
+
#: maximum number of items a range may produce
|
| 25 |
+
MAX_RANGE = 100000
|
| 26 |
+
|
| 27 |
+
#: Unsafe function attributes.
|
| 28 |
+
UNSAFE_FUNCTION_ATTRIBUTES: t.Set[str] = set()
|
| 29 |
+
|
| 30 |
+
#: Unsafe method attributes. Function attributes are unsafe for methods too.
|
| 31 |
+
UNSAFE_METHOD_ATTRIBUTES: t.Set[str] = set()
|
| 32 |
+
|
| 33 |
+
#: unsafe generator attributes.
|
| 34 |
+
UNSAFE_GENERATOR_ATTRIBUTES = {"gi_frame", "gi_code"}
|
| 35 |
+
|
| 36 |
+
#: unsafe attributes on coroutines
|
| 37 |
+
UNSAFE_COROUTINE_ATTRIBUTES = {"cr_frame", "cr_code"}
|
| 38 |
+
|
| 39 |
+
#: unsafe attributes on async generators
|
| 40 |
+
UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}
|
| 41 |
+
|
| 42 |
+
_mutable_spec: t.Tuple[t.Tuple[t.Type[t.Any], t.FrozenSet[str]], ...] = (
|
| 43 |
+
(
|
| 44 |
+
abc.MutableSet,
|
| 45 |
+
frozenset(
|
| 46 |
+
[
|
| 47 |
+
"add",
|
| 48 |
+
"clear",
|
| 49 |
+
"difference_update",
|
| 50 |
+
"discard",
|
| 51 |
+
"pop",
|
| 52 |
+
"remove",
|
| 53 |
+
"symmetric_difference_update",
|
| 54 |
+
"update",
|
| 55 |
+
]
|
| 56 |
+
),
|
| 57 |
+
),
|
| 58 |
+
(
|
| 59 |
+
abc.MutableMapping,
|
| 60 |
+
frozenset(["clear", "pop", "popitem", "setdefault", "update"]),
|
| 61 |
+
),
|
| 62 |
+
(
|
| 63 |
+
abc.MutableSequence,
|
| 64 |
+
frozenset(
|
| 65 |
+
["append", "clear", "pop", "reverse", "insert", "sort", "extend", "remove"]
|
| 66 |
+
),
|
| 67 |
+
),
|
| 68 |
+
(
|
| 69 |
+
deque,
|
| 70 |
+
frozenset(
|
| 71 |
+
[
|
| 72 |
+
"append",
|
| 73 |
+
"appendleft",
|
| 74 |
+
"clear",
|
| 75 |
+
"extend",
|
| 76 |
+
"extendleft",
|
| 77 |
+
"pop",
|
| 78 |
+
"popleft",
|
| 79 |
+
"remove",
|
| 80 |
+
"rotate",
|
| 81 |
+
]
|
| 82 |
+
),
|
| 83 |
+
),
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def safe_range(*args: int) -> range:
|
| 88 |
+
"""A range that can't generate ranges with a length of more than
|
| 89 |
+
MAX_RANGE items.
|
| 90 |
+
"""
|
| 91 |
+
rng = range(*args)
|
| 92 |
+
|
| 93 |
+
if len(rng) > MAX_RANGE:
|
| 94 |
+
raise OverflowError(
|
| 95 |
+
"Range too big. The sandbox blocks ranges larger than"
|
| 96 |
+
f" MAX_RANGE ({MAX_RANGE})."
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
return rng
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def unsafe(f: F) -> F:
|
| 103 |
+
"""Marks a function or method as unsafe.
|
| 104 |
+
|
| 105 |
+
.. code-block: python
|
| 106 |
+
|
| 107 |
+
@unsafe
|
| 108 |
+
def delete(self):
|
| 109 |
+
pass
|
| 110 |
+
"""
|
| 111 |
+
f.unsafe_callable = True # type: ignore
|
| 112 |
+
return f
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def is_internal_attribute(obj: t.Any, attr: str) -> bool:
|
| 116 |
+
"""Test if the attribute given is an internal python attribute. For
|
| 117 |
+
example this function returns `True` for the `func_code` attribute of
|
| 118 |
+
python objects. This is useful if the environment method
|
| 119 |
+
:meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.
|
| 120 |
+
|
| 121 |
+
>>> from jinja2.sandbox import is_internal_attribute
|
| 122 |
+
>>> is_internal_attribute(str, "mro")
|
| 123 |
+
True
|
| 124 |
+
>>> is_internal_attribute(str, "upper")
|
| 125 |
+
False
|
| 126 |
+
"""
|
| 127 |
+
if isinstance(obj, types.FunctionType):
|
| 128 |
+
if attr in UNSAFE_FUNCTION_ATTRIBUTES:
|
| 129 |
+
return True
|
| 130 |
+
elif isinstance(obj, types.MethodType):
|
| 131 |
+
if attr in UNSAFE_FUNCTION_ATTRIBUTES or attr in UNSAFE_METHOD_ATTRIBUTES:
|
| 132 |
+
return True
|
| 133 |
+
elif isinstance(obj, type):
|
| 134 |
+
if attr == "mro":
|
| 135 |
+
return True
|
| 136 |
+
elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):
|
| 137 |
+
return True
|
| 138 |
+
elif isinstance(obj, types.GeneratorType):
|
| 139 |
+
if attr in UNSAFE_GENERATOR_ATTRIBUTES:
|
| 140 |
+
return True
|
| 141 |
+
elif hasattr(types, "CoroutineType") and isinstance(obj, types.CoroutineType):
|
| 142 |
+
if attr in UNSAFE_COROUTINE_ATTRIBUTES:
|
| 143 |
+
return True
|
| 144 |
+
elif hasattr(types, "AsyncGeneratorType") and isinstance(
|
| 145 |
+
obj, types.AsyncGeneratorType
|
| 146 |
+
):
|
| 147 |
+
if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:
|
| 148 |
+
return True
|
| 149 |
+
return attr.startswith("__")
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def modifies_known_mutable(obj: t.Any, attr: str) -> bool:
|
| 153 |
+
"""This function checks if an attribute on a builtin mutable object
|
| 154 |
+
(list, dict, set or deque) or the corresponding ABCs would modify it
|
| 155 |
+
if called.
|
| 156 |
+
|
| 157 |
+
>>> modifies_known_mutable({}, "clear")
|
| 158 |
+
True
|
| 159 |
+
>>> modifies_known_mutable({}, "keys")
|
| 160 |
+
False
|
| 161 |
+
>>> modifies_known_mutable([], "append")
|
| 162 |
+
True
|
| 163 |
+
>>> modifies_known_mutable([], "index")
|
| 164 |
+
False
|
| 165 |
+
|
| 166 |
+
If called with an unsupported object, ``False`` is returned.
|
| 167 |
+
|
| 168 |
+
>>> modifies_known_mutable("foo", "upper")
|
| 169 |
+
False
|
| 170 |
+
"""
|
| 171 |
+
for typespec, unsafe in _mutable_spec:
|
| 172 |
+
if isinstance(obj, typespec):
|
| 173 |
+
return attr in unsafe
|
| 174 |
+
return False
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class SandboxedEnvironment(Environment):
|
| 178 |
+
"""The sandboxed environment. It works like the regular environment but
|
| 179 |
+
tells the compiler to generate sandboxed code. Additionally subclasses of
|
| 180 |
+
this environment may override the methods that tell the runtime what
|
| 181 |
+
attributes or functions are safe to access.
|
| 182 |
+
|
| 183 |
+
If the template tries to access insecure code a :exc:`SecurityError` is
|
| 184 |
+
raised. However also other exceptions may occur during the rendering so
|
| 185 |
+
the caller has to ensure that all exceptions are caught.
|
| 186 |
+
"""
|
| 187 |
+
|
| 188 |
+
sandboxed = True
|
| 189 |
+
|
| 190 |
+
#: default callback table for the binary operators. A copy of this is
|
| 191 |
+
#: available on each instance of a sandboxed environment as
|
| 192 |
+
#: :attr:`binop_table`
|
| 193 |
+
default_binop_table: t.Dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {
|
| 194 |
+
"+": operator.add,
|
| 195 |
+
"-": operator.sub,
|
| 196 |
+
"*": operator.mul,
|
| 197 |
+
"/": operator.truediv,
|
| 198 |
+
"//": operator.floordiv,
|
| 199 |
+
"**": operator.pow,
|
| 200 |
+
"%": operator.mod,
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
#: default callback table for the unary operators. A copy of this is
|
| 204 |
+
#: available on each instance of a sandboxed environment as
|
| 205 |
+
#: :attr:`unop_table`
|
| 206 |
+
default_unop_table: t.Dict[str, t.Callable[[t.Any], t.Any]] = {
|
| 207 |
+
"+": operator.pos,
|
| 208 |
+
"-": operator.neg,
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
#: a set of binary operators that should be intercepted. Each operator
|
| 212 |
+
#: that is added to this set (empty by default) is delegated to the
|
| 213 |
+
#: :meth:`call_binop` method that will perform the operator. The default
|
| 214 |
+
#: operator callback is specified by :attr:`binop_table`.
|
| 215 |
+
#:
|
| 216 |
+
#: The following binary operators are interceptable:
|
| 217 |
+
#: ``//``, ``%``, ``+``, ``*``, ``-``, ``/``, and ``**``
|
| 218 |
+
#:
|
| 219 |
+
#: The default operation form the operator table corresponds to the
|
| 220 |
+
#: builtin function. Intercepted calls are always slower than the native
|
| 221 |
+
#: operator call, so make sure only to intercept the ones you are
|
| 222 |
+
#: interested in.
|
| 223 |
+
#:
|
| 224 |
+
#: .. versionadded:: 2.6
|
| 225 |
+
intercepted_binops: t.FrozenSet[str] = frozenset()
|
| 226 |
+
|
| 227 |
+
#: a set of unary operators that should be intercepted. Each operator
|
| 228 |
+
#: that is added to this set (empty by default) is delegated to the
|
| 229 |
+
#: :meth:`call_unop` method that will perform the operator. The default
|
| 230 |
+
#: operator callback is specified by :attr:`unop_table`.
|
| 231 |
+
#:
|
| 232 |
+
#: The following unary operators are interceptable: ``+``, ``-``
|
| 233 |
+
#:
|
| 234 |
+
#: The default operation form the operator table corresponds to the
|
| 235 |
+
#: builtin function. Intercepted calls are always slower than the native
|
| 236 |
+
#: operator call, so make sure only to intercept the ones you are
|
| 237 |
+
#: interested in.
|
| 238 |
+
#:
|
| 239 |
+
#: .. versionadded:: 2.6
|
| 240 |
+
intercepted_unops: t.FrozenSet[str] = frozenset()
|
| 241 |
+
|
| 242 |
+
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
|
| 243 |
+
super().__init__(*args, **kwargs)
|
| 244 |
+
self.globals["range"] = safe_range
|
| 245 |
+
self.binop_table = self.default_binop_table.copy()
|
| 246 |
+
self.unop_table = self.default_unop_table.copy()
|
| 247 |
+
|
| 248 |
+
def is_safe_attribute(self, obj: t.Any, attr: str, value: t.Any) -> bool:
|
| 249 |
+
"""The sandboxed environment will call this method to check if the
|
| 250 |
+
attribute of an object is safe to access. Per default all attributes
|
| 251 |
+
starting with an underscore are considered private as well as the
|
| 252 |
+
special attributes of internal python objects as returned by the
|
| 253 |
+
:func:`is_internal_attribute` function.
|
| 254 |
+
"""
|
| 255 |
+
return not (attr.startswith("_") or is_internal_attribute(obj, attr))
|
| 256 |
+
|
| 257 |
+
def is_safe_callable(self, obj: t.Any) -> bool:
|
| 258 |
+
"""Check if an object is safely callable. By default callables
|
| 259 |
+
are considered safe unless decorated with :func:`unsafe`.
|
| 260 |
+
|
| 261 |
+
This also recognizes the Django convention of setting
|
| 262 |
+
``func.alters_data = True``.
|
| 263 |
+
"""
|
| 264 |
+
return not (
|
| 265 |
+
getattr(obj, "unsafe_callable", False) or getattr(obj, "alters_data", False)
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
def call_binop(
|
| 269 |
+
self, context: Context, operator: str, left: t.Any, right: t.Any
|
| 270 |
+
) -> t.Any:
|
| 271 |
+
"""For intercepted binary operator calls (:meth:`intercepted_binops`)
|
| 272 |
+
this function is executed instead of the builtin operator. This can
|
| 273 |
+
be used to fine tune the behavior of certain operators.
|
| 274 |
+
|
| 275 |
+
.. versionadded:: 2.6
|
| 276 |
+
"""
|
| 277 |
+
return self.binop_table[operator](left, right)
|
| 278 |
+
|
| 279 |
+
def call_unop(self, context: Context, operator: str, arg: t.Any) -> t.Any:
|
| 280 |
+
"""For intercepted unary operator calls (:meth:`intercepted_unops`)
|
| 281 |
+
this function is executed instead of the builtin operator. This can
|
| 282 |
+
be used to fine tune the behavior of certain operators.
|
| 283 |
+
|
| 284 |
+
.. versionadded:: 2.6
|
| 285 |
+
"""
|
| 286 |
+
return self.unop_table[operator](arg)
|
| 287 |
+
|
| 288 |
+
def getitem(
|
| 289 |
+
self, obj: t.Any, argument: t.Union[str, t.Any]
|
| 290 |
+
) -> t.Union[t.Any, Undefined]:
|
| 291 |
+
"""Subscribe an object from sandboxed code."""
|
| 292 |
+
try:
|
| 293 |
+
return obj[argument]
|
| 294 |
+
except (TypeError, LookupError):
|
| 295 |
+
if isinstance(argument, str):
|
| 296 |
+
try:
|
| 297 |
+
attr = str(argument)
|
| 298 |
+
except Exception:
|
| 299 |
+
pass
|
| 300 |
+
else:
|
| 301 |
+
try:
|
| 302 |
+
value = getattr(obj, attr)
|
| 303 |
+
except AttributeError:
|
| 304 |
+
pass
|
| 305 |
+
else:
|
| 306 |
+
fmt = self.wrap_str_format(value)
|
| 307 |
+
if fmt is not None:
|
| 308 |
+
return fmt
|
| 309 |
+
if self.is_safe_attribute(obj, argument, value):
|
| 310 |
+
return value
|
| 311 |
+
return self.unsafe_undefined(obj, argument)
|
| 312 |
+
return self.undefined(obj=obj, name=argument)
|
| 313 |
+
|
| 314 |
+
def getattr(self, obj: t.Any, attribute: str) -> t.Union[t.Any, Undefined]:
|
| 315 |
+
"""Subscribe an object from sandboxed code and prefer the
|
| 316 |
+
attribute. The attribute passed *must* be a bytestring.
|
| 317 |
+
"""
|
| 318 |
+
try:
|
| 319 |
+
value = getattr(obj, attribute)
|
| 320 |
+
except AttributeError:
|
| 321 |
+
try:
|
| 322 |
+
return obj[attribute]
|
| 323 |
+
except (TypeError, LookupError):
|
| 324 |
+
pass
|
| 325 |
+
else:
|
| 326 |
+
fmt = self.wrap_str_format(value)
|
| 327 |
+
if fmt is not None:
|
| 328 |
+
return fmt
|
| 329 |
+
if self.is_safe_attribute(obj, attribute, value):
|
| 330 |
+
return value
|
| 331 |
+
return self.unsafe_undefined(obj, attribute)
|
| 332 |
+
return self.undefined(obj=obj, name=attribute)
|
| 333 |
+
|
| 334 |
+
def unsafe_undefined(self, obj: t.Any, attribute: str) -> Undefined:
|
| 335 |
+
"""Return an undefined object for unsafe attributes."""
|
| 336 |
+
return self.undefined(
|
| 337 |
+
f"access to attribute {attribute!r} of"
|
| 338 |
+
f" {type(obj).__name__!r} object is unsafe.",
|
| 339 |
+
name=attribute,
|
| 340 |
+
obj=obj,
|
| 341 |
+
exc=SecurityError,
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
def wrap_str_format(self, value: t.Any) -> t.Optional[t.Callable[..., str]]:
|
| 345 |
+
"""If the given value is a ``str.format`` or ``str.format_map`` method,
|
| 346 |
+
return a new function than handles sandboxing. This is done at access
|
| 347 |
+
rather than in :meth:`call`, so that calls made without ``call`` are
|
| 348 |
+
also sandboxed.
|
| 349 |
+
"""
|
| 350 |
+
if not isinstance(
|
| 351 |
+
value, (types.MethodType, types.BuiltinMethodType)
|
| 352 |
+
) or value.__name__ not in ("format", "format_map"):
|
| 353 |
+
return None
|
| 354 |
+
|
| 355 |
+
f_self: t.Any = value.__self__
|
| 356 |
+
|
| 357 |
+
if not isinstance(f_self, str):
|
| 358 |
+
return None
|
| 359 |
+
|
| 360 |
+
str_type: t.Type[str] = type(f_self)
|
| 361 |
+
is_format_map = value.__name__ == "format_map"
|
| 362 |
+
formatter: SandboxedFormatter
|
| 363 |
+
|
| 364 |
+
if isinstance(f_self, Markup):
|
| 365 |
+
formatter = SandboxedEscapeFormatter(self, escape=f_self.escape)
|
| 366 |
+
else:
|
| 367 |
+
formatter = SandboxedFormatter(self)
|
| 368 |
+
|
| 369 |
+
vformat = formatter.vformat
|
| 370 |
+
|
| 371 |
+
def wrapper(*args: t.Any, **kwargs: t.Any) -> str:
|
| 372 |
+
if is_format_map:
|
| 373 |
+
if kwargs:
|
| 374 |
+
raise TypeError("format_map() takes no keyword arguments")
|
| 375 |
+
|
| 376 |
+
if len(args) != 1:
|
| 377 |
+
raise TypeError(
|
| 378 |
+
f"format_map() takes exactly one argument ({len(args)} given)"
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
kwargs = args[0]
|
| 382 |
+
args = ()
|
| 383 |
+
|
| 384 |
+
return str_type(vformat(f_self, args, kwargs))
|
| 385 |
+
|
| 386 |
+
return update_wrapper(wrapper, value)
|
| 387 |
+
|
| 388 |
+
def call(
|
| 389 |
+
__self, # noqa: B902
|
| 390 |
+
__context: Context,
|
| 391 |
+
__obj: t.Any,
|
| 392 |
+
*args: t.Any,
|
| 393 |
+
**kwargs: t.Any,
|
| 394 |
+
) -> t.Any:
|
| 395 |
+
"""Call an object from sandboxed code."""
|
| 396 |
+
|
| 397 |
+
# the double prefixes are to avoid double keyword argument
|
| 398 |
+
# errors when proxying the call.
|
| 399 |
+
if not __self.is_safe_callable(__obj):
|
| 400 |
+
raise SecurityError(f"{__obj!r} is not safely callable")
|
| 401 |
+
return __context.call(__obj, *args, **kwargs)
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
class ImmutableSandboxedEnvironment(SandboxedEnvironment):
|
| 405 |
+
"""Works exactly like the regular `SandboxedEnvironment` but does not
|
| 406 |
+
permit modifications on the builtin mutable objects `list`, `set`, and
|
| 407 |
+
`dict` by using the :func:`modifies_known_mutable` function.
|
| 408 |
+
"""
|
| 409 |
+
|
| 410 |
+
def is_safe_attribute(self, obj: t.Any, attr: str, value: t.Any) -> bool:
|
| 411 |
+
if not super().is_safe_attribute(obj, attr, value):
|
| 412 |
+
return False
|
| 413 |
+
|
| 414 |
+
return not modifies_known_mutable(obj, attr)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
class SandboxedFormatter(Formatter):
|
| 418 |
+
def __init__(self, env: Environment, **kwargs: t.Any) -> None:
|
| 419 |
+
self._env = env
|
| 420 |
+
super().__init__(**kwargs)
|
| 421 |
+
|
| 422 |
+
def get_field(
|
| 423 |
+
self, field_name: str, args: t.Sequence[t.Any], kwargs: t.Mapping[str, t.Any]
|
| 424 |
+
) -> t.Tuple[t.Any, str]:
|
| 425 |
+
first, rest = formatter_field_name_split(field_name)
|
| 426 |
+
obj = self.get_value(first, args, kwargs)
|
| 427 |
+
for is_attr, i in rest:
|
| 428 |
+
if is_attr:
|
| 429 |
+
obj = self._env.getattr(obj, i)
|
| 430 |
+
else:
|
| 431 |
+
obj = self._env.getitem(obj, i)
|
| 432 |
+
return obj, first
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
class SandboxedEscapeFormatter(SandboxedFormatter, EscapeFormatter):
|
| 436 |
+
pass
|
janus/lib/python3.10/site-packages/networkx-3.4.2.dist-info/REQUESTED
ADDED
|
File without changes
|
janus/lib/python3.10/site-packages/networkx-3.4.2.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
networkx
|