scrapy / scrapy
1 7
import asyncio
2 7
from contextlib import suppress
3

4 7
from twisted.internet import asyncioreactor, error
5

6 7
from scrapy.utils.misc import load_object
7

8

9 7
def listen_tcp(portrange, host, factory):
10
    """Like reactor.listenTCP but tries different ports in a range."""
11 7
    from twisted.internet import reactor
12 7
    if len(portrange) > 2:
13 0
        raise ValueError(f"invalid portrange: {portrange}")
14 7
    if not portrange:
15 0
        return reactor.listenTCP(0, factory, interface=host)
16 7
    if not hasattr(portrange, '__iter__'):
17 0
        return reactor.listenTCP(portrange, factory, interface=host)
18 7
    if len(portrange) == 1:
19 0
        return reactor.listenTCP(portrange[0], factory, interface=host)
20 7
    for x in range(portrange[0], portrange[1] + 1):
21 7
        try:
22 7
            return reactor.listenTCP(x, factory, interface=host)
23 7
        except error.CannotListenError:
24 7
            if x == portrange[1]:
25 0
                raise
26

27

28 7
class CallLaterOnce:
29
    """Schedule a function to be called in the next reactor loop, but only if
30
    it hasn't been already scheduled since the last time it ran.
31
    """
32

33 7
    def __init__(self, func, *a, **kw):
34 7
        self._func = func
35 7
        self._a = a
36 7
        self._kw = kw
37 7
        self._call = None
38

39 7
    def schedule(self, delay=0):
40 7
        from twisted.internet import reactor
41 7
        if self._call is None:
42 7
            self._call = reactor.callLater(delay, self)
43

44 7
    def cancel(self):
45 7
        if self._call:
46 7
            self._call.cancel()
47

48 7
    def __call__(self):
49 7
        self._call = None
50 7
        return self._func(*self._a, **self._kw)
51

52

53 7
def install_reactor(reactor_path, event_loop_path=None):
54
    """Installs the :mod:`~twisted.internet.reactor` with the specified
55
    import path. Also installs the asyncio event loop with the specified import
56
    path if the asyncio reactor is enabled"""
57 7
    reactor_class = load_object(reactor_path)
58 7
    if reactor_class is asyncioreactor.AsyncioSelectorReactor:
59 7
        with suppress(error.ReactorAlreadyInstalledError):
60 7
            if event_loop_path is not None:
61 2
                event_loop_class = load_object(event_loop_path)
62 2
                event_loop = event_loop_class()
63 2
                asyncio.set_event_loop(event_loop)
64
            else:
65 7
                event_loop = asyncio.get_event_loop()
66 7
            asyncioreactor.install(eventloop=event_loop)
67
    else:
68 7
        *module, _ = reactor_path.split(".")
69 7
        installer_path = module + ["install"]
70 7
        installer = load_object(".".join(installer_path))
71 7
        with suppress(error.ReactorAlreadyInstalledError):
72 7
            installer()
73

74

75 7
def verify_installed_reactor(reactor_path):
76
    """Raises :exc:`Exception` if the installed
77
    :mod:`~twisted.internet.reactor` does not match the specified import
78
    path."""
79 7
    from twisted.internet import reactor
80 7
    reactor_class = load_object(reactor_path)
81 7
    if not isinstance(reactor, reactor_class):
82 5
        msg = ("The installed reactor "
83
               f"({reactor.__module__}.{reactor.__class__.__name__}) does not "
84
               f"match the requested one ({reactor_path})")
85 5
        raise Exception(msg)
86

87

88 7
def is_asyncio_reactor_installed():
89 7
    from twisted.internet import reactor
90 7
    return isinstance(reactor, asyncioreactor.AsyncioSelectorReactor)

Read our documentation on viewing source code .

Loading