Crochet

2.1.1 · active · verified Thu Apr 16

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.

Common errors

Warnings

Install

Imports

Quickstart

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.")

view raw JSON →