File: twisted_250_monkeypatches.py

package info (click to toggle)
python-scrapy 0.8-3
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 2,904 kB
  • ctags: 2,981
  • sloc: python: 15,349; xml: 199; makefile: 68; sql: 64; sh: 34
file content (48 lines) | stat: -rw-r--r-- 1,577 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
Monkey patches for supporting Twisted 2.5.0

NOTE: This module must not fail if twisted module is not available.
"""

# This function comes bundled with Twisted 8.x and above
def add_missing_blockingCallFromThread():
    import Queue
    from twisted.internet import defer
    from twisted.python import failure

    def blockingCallFromThread(reactor, f, *a, **kw):
        """
        Run a function in the reactor from a thread, and wait for the result
        synchronously, i.e. until the callback chain returned by the function
        get a result.

        @param reactor: The L{IReactorThreads} provider which will be used to
            schedule the function call.
        @param f: the callable to run in the reactor thread
        @type f: any callable.
        @param a: the arguments to pass to C{f}.
        @param kw: the keyword arguments to pass to C{f}.

        @return: the result of the callback chain.
        @raise: any error raised during the callback chain.
        """
        queue = Queue.Queue()
        def _callFromThread():
            result = defer.maybeDeferred(f, *a, **kw)
            result.addBoth(queue.put)
        reactor.callFromThread(_callFromThread)
        result = queue.get()
        if isinstance(result, failure.Failure):
            result.raiseException()
        return result

    from twisted.internet import threads
    threads.blockingCallFromThread = blockingCallFromThread

try:
    import twisted
    if twisted.__version__ < '8.0.0':
        add_missing_blockingCallFromThread()
except ImportError:
    pass