Debian Codegraph @

docs/api.rst

raw
1 Using Crochet
2 -------------
3
4 Using Crochet involves three parts: reactor setup, defining functions that
5 call into Twisted's reactor, and using those functions.
6
7
8 Setup
9 ^^^^^
10
11 Crochet does a number of things for you as part of setup. Most significantly,
12 it runs Twisted's reactor in a thread it manages. Doing setup is easy, just
13 call the ``setup()`` function:
14
15 .. code-block:: python
16
17 from crochet import setup
18 setup()
19
20 Since Crochet is intended to be used as a library, multiple calls work just
21 fine; if more than one library does ``crochet.setup()`` only the first one
22 will do anything.
23
24
25 @wait_for: Blocking calls into Twisted
26 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
27
28 Now that you've got the reactor running, the next stage is defining some
29 functions that will run inside the Twisted reactor thread. Twisted's APIs are
30 not thread-safe, and so they cannot be called directly from another
31 thread. Moreover, results may not be available immediately. The easiest way to
32 deal with these issues is to decorate a function that calls Twisted APIs with
33 ``crochet.wait_for``.
34
35 * When the decorated function is called, the code will not run in the calling
36 thread, but rather in the reactor thread.
37 * The function blocks until a result is available from the code running in the
38 Twisted thread. The returned result is the result of running the code; if
39 the code throws an exception, an exception is thrown.
40 * If the underlying code returns a ``Deferred``, it is handled transparently;
41 its results are extracted and passed to the caller.
42 * ``crochet.wait_for`` takes a ``timeout`` argument, a ``float`` indicating
43 the number of seconds to wait until a result is available. If the given
44 number of seconds pass and the underlying operation is still unfinished a
45 ``crochet.TimeoutError`` exception is raised, and the wrapped ``Deferred``
46 is canceled. If the underlying API supports cancellation this might free up
47 any unused resources, close outgoing connections etc., but cancellation is
48 not guaranteed and should not be relied on.
49
50 To see what this means, let's return to the first example in the
51 documentation:
52
53 .. literalinclude:: ../examples/blockingdns.py
54
55 Twisted's ``lookupAddress()`` call returns a ``Deferred``, but the code calling the
56 decorated ``gethostbyname()`` doesn't know that. As far as the caller
57 concerned is just calling a blocking function that returns a result or raises
58 an exception. Run on the command line with a valid domain we get::
59
60 $ python blockingdns.py twistedmatrix.com
61 twistedmatrix.com -> 66.35.39.66
62
63 If we try to call the function with an invalid domain, we get back an exception::
64
65 $ python blockingdns.py doesnotexist
66 Trace back (most recent call last):
67 File "examples/blockingdns.py", line 33, in <module>
68 ip = gethostbyname(name)
69 File "/home/itamar/crochet/crochet/_eventloop.py", line 434, in wrapper
70 return eventual_result.wait(timeout)
71 File "/home/itamar/crochet/crochet/_eventloop.py", line 216, in wait
72 result.raiseException()
73 File "<string>", line 2, in raiseException
74 twisted.names.error.DNSNameError: <Message id=36791 rCode=3 maxSize=0 flags=answer,recDes,recAv queries=[Query('doesnotexist', 1, 1)] authority=[<RR name= type=SOA class=IN ttl=1694s auth=False>]>
75
76 You can, similarly, wrap an ``async`` function:
77
78 .. literalinclude:: ../examples/async.py
79
80
81 @run_in_reactor: Asynchronous results
82 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
83
84 ``wait_for`` is implemented using ``run_in_reactor``, a more sophisticated and
85 lower-level API. Rather than waiting until a result is available, it returns a
86 special object supporting multiple attempts to retrieve results, as well as
87 manual cancellation. This can be useful for running tasks "in the background",
88 i.e. asynchronously, as opposed to blocking and waiting for them to finish.
89
90 Decorating a function that calls Twisted APIs with ``run_in_reactor`` has two
91 consequences:
92
93 * When the function is called, the code will not run in the calling thread,
94 but rather in the reactor thread.
95 * The return result from a decorated function is an ``EventualResult``
96 instance, wrapping the result of the underlying code, with built-in
97 support for functions that return ``Deferred`` instances as well as
98 ``async`` functions.
99
100 ``EventualResult`` has the following basic methods:
101
102 * ``wait(timeout)``: Return the result when it becomes available; if the
103 result is an exception it will be raised. The timeout argument is a
104 ``float`` indicating a number of seconds; ``wait()`` will throw
105 ``crochet.TimeoutError`` if the timeout is hit.
106 * ``cancel()``: Cancel the operation tied to the underlying
107 ``Deferred``. Many, but not all, ``Deferred`` results returned from Twisted
108 allow the underlying operation to be canceled. Even if implemented,
109 cancellation may not be possible for a variety of reasons, e.g. it may be
110 too late. Its main purpose to free up no longer used resources, and it
111 should not be relied on otherwise.
112
113 There are also some more specialized methods:
114
115 * ``original_failure()`` returns the underlying Twisted `Failure`_ object if
116 your result was a raised exception, allowing you to print the original
117 traceback that caused the exception. This is necessary because the default
118 exception you will see raised from ``EventualResult.wait()`` won't include
119 the stack from the underlying Twisted code where the exception originated.
120 * ``stash()``: Sometimes you want to store the ``EventualResult`` in memory
121 for later retrieval. This is specifically useful when you want to store a
122 reference to the ``EventualResult`` in a web session like Flask's (see the
123 example below). ``stash()`` stores the ``EventualResult`` in memory, and
124 returns an integer uid that can be used to retrieve the result using
125 ``crochet.retrieve_result(uid)``. Note that retrieval works only once per
126 uid. You will need the stash the ``EventualResult`` again (with a new
127 resulting uid) if you want to retrieve it again later.
128
129 In the following example, you can see all of these APIs in use. For each user
130 session, a download is started in the background. Subsequent page refreshes
131 will eventually show the downloaded page.
132
133 .. literalinclude:: ../examples/downloader.py
134
135 .. _Failure: https://twistedmatrix.com/documents/current/api/twisted.python.failure.Failure.html
136
137 Using Crochet from Twisted applications
138 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
139
140 If your application is already planning on running the Twisted reactor itself
141 (e.g. you're using Twisted as a WSGI container), Crochet's default behavior of
142 running the reactor in a thread is a problem. To solve this, Crochet provides
143 the ``no_setup()`` function, which causes future calls to ``setup()`` to do
144 nothing. Thus, an application that will run the Twisted reactor but also wants
145 to use a Crochet-using library must run it first:
146
147 .. code-block:: python
148
149 from crochet import no_setup
150 no_setup()
151 # Only now do we import libraries that might run crochet.setup():
152 import blockinglib
153
154 # ... setup application ...
155
156 from twisted.internet import reactor
157 reactor.run()
158
159
160 Unit testing
161 ^^^^^^^^^^^^
162
163 Both ``@wait_for`` and ``@run_in_reactor`` expose the underlying Twisted
164 function via a ``__wrapped__`` attribute. This allows unit testing of the
165 Twisted code without having to go through the Crochet layer.
166
167 .. literalinclude:: ../examples/testing.py
168
169 When run, this gives the following output::
170
171 add(1, 2) returns EventualResult:
172 <crochet._eventloop.EventualResult object at 0x2e8b390>
173 add.__wrapped__(1, 2) returns result of underlying function:
174 3