Crochet is an MIT-licensed library that makes it easier to use Twisted from regular blocking code. Some use cases include:

 * Easily use Twisted from a blocking framework like Django or Flask.
 * Write a library that provides a blocking API, but uses Twisted for
   its implementation.
 * Port blocking code to Twisted more easily, by keeping a backwards
   compatibility layer.
 * Allow normal Twisted programs that use threads to interact with
   Twisted more cleanly from their threaded parts. For example this can
   be useful when using Twisted as a WSGI container.

This is a bugfix release, recommended for all users of Crochet.

Crochet can be downloaded from https://pypi.python.org/pypi/crochet or by running:

    $ pip install crochet

Documentation can be found at http://crochet.readthedocs.org <https://crochet.readthedocs.org/>

Bugs and feature requests should be filed at the project https://github.com/itamarst/crochet

Here’s an example of a program using Crochet. Notice that you get a completely blocking interface to Twisted and do not need to run the Twisted reactor, the event loop, yourself.

#!/usr/bin/python
"""
Do a DNS lookup using Twisted's APIs.
"""
from  __future__  import  print_function

# The Twisted code we'll be using:
from  twisted.names  import  client

from  crochet  import  setup,  wait_for
setup()


# Crochet layer, wrapping Twisted's DNS library in a blocking call.
@wait_for(timeout=5.0)
def  gethostbyname(name):
    """Lookup the IP of a given hostname.

    Unlike socket.gethostbyname() which can take an arbitrary amount of time
    to finish, this function will raise crochet.TimeoutError if more than 5
    seconds elapse without an answer being received.
    """
    d  =  client.lookupAddress(name)
    d.addCallback(lambda  result:  result[0][0].payload.dottedQuad())
    return  d


if  __name__  ==  '__main__':
    # Application code using the public API - notice it works in a normal
    # blocking manner, with no event loop visible:
    import  sys
    name  =  sys.argv[1]
    ip  =  gethostbyname(name)
    print(name,  "->",  ip)

Run on the command line:

$ python blockingdns.py twistedmatrix.com
twistedmatrix.com -> 66.35.39.66

--
https://mail.python.org/mailman/listinfo/python-announce-list

       Support the Python Software Foundation:
       http://www.python.org/psf/donations/

Reply via email to