Tuesday, April 9, 2013

Presenting Crochet: Use Twisted as a library

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

from crochet import setup, in_reactor
setup()


@in_reactor
def mx(reactor, domain):
    """
    Return list of MX domains for a given domain.
    """
    from twisted.names.client import lookupMailExchange
    def got_records(result):
        hosts, authorities, additional = result
        return [str(record.name) for record in additional]
    d = lookupMailExchange(domain)
    d.addCallback(got_records)
    return d


def main(domain):
    print("Mail servers for %s:" % (domain,))
    for mailserver in mx(domain).wait():
        print(mailserver)


if __name__ == '__main__':
    import sys
    main(sys.argv[1])
When we run it on the command line, output looks this:
$ python mxquery.py gmail.com
Mail servers for gmail.com:
alt2.gmail-smtp-in.l.google.com
alt2.gmail-smtp-in.l.google.com
alt3.gmail-smtp-in.l.google.com
alt3.gmail-smtp-in.l.google.com
alt4.gmail-smtp-in.l.google.com
alt4.gmail-smtp-in.l.google.com
alt1.gmail-smtp-in.l.google.com
gmail-smtp-in.l.google.com
gmail-smtp-in.l.google.com
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.

No comments:

Post a Comment