Twisted is an event-driven framework; by default it expects to run the reactor event loop in your main thread to drive your application. If however you're writing a Django or Flask application you may want to use Twisted as just another library. Unless you choose to use Twisted as a WSGI container, this requires you to run the reactor in a thread. Today I am happy to announce Crochet, which makes using Twisted even easier in this situation.

Here's an example program using Crochet, allowing it to easily use Twisted from a normal, blocking command-line tool:

from __future__ import print_function<br /><br />from crochet import setup, in_reactor<br />setup()<br /><br /><br />@in_reactor<br />def mx(reactor, domain):<br />    """<br />    Return list of MX domains for a given domain.<br />    """<br />    from twisted.names.client import lookupMailExchange<br />    def got_records(result):<br />        hosts, authorities, additional = result<br />        return [str(record.name) for record in additional]<br />    d = lookupMailExchange(domain)<br />    d.addCallback(got_records)<br />    return d<br /><br /><br />def main(domain):<br />    print("Mail servers for %s:" % (domain,))<br />    for mailserver in mx(domain).wait():<br />        print(mailserver)<br /><br /><br />if __name__ == '__main__':<br />    import sys<br />    main(sys.argv[1])<br />
When we run it on the command line, output looks this:
$ python mxquery.py gmail.com<br />Mail servers for gmail.com:<br />alt2.gmail-smtp-in.l.google.com<br />alt2.gmail-smtp-in.l.google.com<br />alt3.gmail-smtp-in.l.google.com<br />alt3.gmail-smtp-in.l.google.com<br />alt4.gmail-smtp-in.l.google.com<br />alt4.gmail-smtp-in.l.google.com<br />alt1.gmail-smtp-in.l.google.com<br />gmail-smtp-in.l.google.com<br />gmail-smtp-in.l.google.com<br />
The library provides much more functionality, but that's the gist of it: it runs and stops the Twisted reactor for you, and wraps asynchronous results in a blocking API. If you'd like to try out Crochet, or learn more about its other features, visit Crochet's PyPI page.