Registry / http-networking / crochet

crochet

JSON →
library2.1.1pypypi✓ verified 86d ago

Crochet is an MIT-licensed Python library that simplifies the integration of Twisted, an asynchronous networking framework, into regular blocking code. It transparently manages the Twisted reactor in a separate thread, allowing developers to call Twisted APIs from blocking applications like Django or Flask, or to create blocking APIs backed by Twisted. The library is currently at version 2.1.1 and is in a mature state, with development being slow due to its stable nature.

pip install crochet
INSTALL
IMPORT
SIG · CROCHET
C
crochet
http-networkingpythonv2.1.1
Install
4.7s avg
Import
544ms
Disk
55MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.1.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 0.558s · 53.3MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 4.7s · import 0.529s · 54MB
55MB installed
● package 55MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

setup
from crochet import setup
Initializes the Crochet library, starts the Twisted reactor in a thread, and connects Twisted's logs to Python's standard logging. Must be called once before using other Crochet features.
wait_for
from crochet import wait_for
A decorator factory that makes an asynchronous Twisted function callable from blocking code, blocking until a result or timeout occurs.
run_in_reactor
from crochet import run_in_reactor
A decorator that ensures the wrapped function runs in the Twisted reactor thread, returning an EventualResult for later blocking retrieval.
TimeoutError
from crochet import TimeoutError
Exception raised by `wait_for` if the decorated function exceeds its specified timeout.

This quickstart demonstrates how to use `crochet.setup()` to initialize the library and `crochet.wait_for` to wrap an asynchronous Twisted function, making it callable from synchronous Python code. It includes examples of successful execution, handling `TimeoutError`, and propagating exceptions from the Twisted reactor thread back to the blocking caller. Ensure you have `twisted` installed (`pip install twisted`) to run this example.

from crochet import setup, wait_for, TimeoutError from twisted.internet import defer import time import logging import os # Configure basic logging to see Twisted output logging.basicConfig(level=logging.INFO) # Initialize crochet - this starts the Twisted reactor in a thread setup() @wait_for(timeout=5.0) def long_running_twisted_task(duration): d = defer.Deferred() # Simulate an asynchronous operation in Twisted's reactor thread def _complete_task(): if os.environ.get('SIMULATE_FAILURE') == '1': d.err(ValueError("Simulated Twisted failure!")) else: d.callback(f"Task completed in {duration} seconds") from twisted.internet import reactor reactor.callLater(duration, _complete_task) return d if __name__ == "__main__": print("Starting Crochet example...") try: # Call the Twisted-backed function from blocking code result = long_running_twisted_task(2.0) print(f"Blocking call returned: {result}") # Demonstrate a timeout print("\nAttempting a task that will timeout...") try: long_running_twisted_task(6.0) # Will timeout after 5 seconds except TimeoutError: print("Caught expected TimeoutError!") # Demonstrate a Twisted error propagating print("\nAttempting a task that will fail in Twisted...") os.environ['SIMULATE_FAILURE'] = '1' try: long_running_twisted_task(1.0) except ValueError as e: print(f"Caught expected ValueError: {e}") finally: del os.environ['SIMULATE_FAILURE'] except Exception as e: print(f"An unexpected error occurred: {e}") finally: print("Crochet example finished.")
Debug
Known issues
breakingCrochet version 2.1.0 dropped support for Python 3.6 and 3.7. Ensure your environment uses Python 3.8 or newer.
fix
Upgrade your Python interpreter to version 3.8 or higher, or pin your crochet dependency to '<2.1.0'.
affects: >=2.1.0
gotchaThe `crochet.setup()` function must be called exactly once before using any other Crochet functionality. Calling it multiple times is harmless, but not calling it at all will lead to runtime errors when attempting to use decorators or `EventualResult`.
fix
Ensure `crochet.setup()` is called early in your application's lifecycle, typically at module import time or application startup.
affects: All
gotchaWhen using `@wait_for`, if the underlying Twisted operation does not complete within the specified `timeout` duration, a `crochet.TimeoutError` will be raised. This means the blocking call will be interrupted.
fix
Handle `crochet.TimeoutError` in your blocking code. Adjust the `timeout` parameter in `@wait_for` based on the expected duration of the asynchronous operation, or implement retry logic.
affects: All
Errors
Common errors & fixes
RuntimeError: The Twisted reactor is not running, or has not been initialized by crochet.
`crochet.setup()` has not been called before attempting to use `@wait_for` or `EventualResult`.
fix
Add `from crochet import setup; setup()` to the initialization section of your application.
crochet.TimeoutError: Waited for 5.0 seconds
An operation decorated with `@wait_for(timeout=X)` exceeded the allowed X seconds, or the Twisted reactor got stuck.
fix
Increase the `timeout` parameter in the `@wait_for` decorator if the operation legitimately takes longer, or debug the Twisted code to identify why it's not completing.
ImportError: cannot import name 'wait_for' from 'crochet'
Attempting to import `wait_for` from a very old version of crochet, or a typo in the import statement.
fix
Ensure `crochet` is installed and updated to a recent version (`pip install --upgrade crochet`). The common import is `from crochet import wait_for`.
Upgrade
Version history
2.1.1latest on PyPI · released Jul 1, 2023
Audit
Dependencies
twistedrequiredCore dependency for asynchronous operations.
wraptrequiredUsed for decorator functionality.
Agent activity
12 hits · last 30 days
node
10
Amazon
1
OpenAI (training)
1
Resources
crochet — pip install crochet · libregistry