| 1 |
Best Practices |
| 2 |
-------------- |
| 3 |
|
| 4 |
Hide Twisted and Crochet |
| 5 |
^^^^^^^^^^^^^^^^^^^^^^^^ |
| 6 |
|
| 7 |
Consider some synchronous do-one-thing-after-the-other application code that |
| 8 |
wants to use event-driven Twisted-using code. We have two threads at a |
| 9 |
minimum: the application thread(s) and the reactor thread. There are also |
| 10 |
multiple layers of code involved in this interaction: |
| 11 |
|
| 12 |
* **Twisted code:** Should only be called in reactor thread. This may be code |
| 13 |
from the Twisted package itself, or more likely code you have written that |
| 14 |
is built on top of Twisted. |
| 15 |
* **@wait_for/@run_in_reactor wrappers:** The body of the functions |
| 16 |
runs in the reactor thread... but the caller should be in the application |
| 17 |
thread. |
| 18 |
* **The application code:** Runs in the application thread(s), expects |
| 19 |
synchronous/blocking calls. |
| 20 |
|
| 21 |
Sometimes the first two layers suffice, but there are some issues with only |
| 22 |
having these. First, if you're using ``@run_in_reactor`` it requires the |
| 23 |
application code to understand Crochet's API, i.e. ``EventualResult`` |
| 24 |
objects. Second, if the wrapped function returns an object that expects to |
| 25 |
interact with Twisted, the application code will not be able to use that |
| 26 |
object since it will be called in the wrong thread. |
| 27 |
|
| 28 |
A better solution is to have an additional layer in-between the application |
| 29 |
code and ``@wait_for/@run_in_reactor`` wrappers. This layer can hide |
| 30 |
the details of the Crochet API and wrap returned Twisted objects if |
| 31 |
necessary. As a result the application code simply seems a normal API, with no |
| 32 |
need to understand ``EventualResult`` objects or Twisted. |
| 33 |
|
| 34 |
In the following example the different layers of the code demonstrate this |
| 35 |
separation: ``_ExchangeRate`` is just Twisted code, and ``ExchangeRate`` |
| 36 |
provides a blocking wrapper using Crochet. |
| 37 |
|
| 38 |
.. literalinclude:: ../examples/scheduling.py |
| 39 |
|
| 40 |
|
| 41 |
Minimize decorated code |
| 42 |
^^^^^^^^^^^^^^^^^^^^^^^ |
| 43 |
|
| 44 |
It's best to have as little code as possible in the |
| 45 |
``@wait_for/@run_in_reactor`` wrappers. As this code straddles two |
| 46 |
worlds (or at least, two threads) it is more difficult to unit test. Having an |
| 47 |
extra layer between this code and the application code is also useful in this |
| 48 |
regard as well: Twisted code can be pushed into the lower-level Twisted layer, |
| 49 |
and code hiding the Twisted details from the application code can be pushed |
| 50 |
into the higher-level layer. |