personal blog

Posts Tagged "twisted"

Non-blocking use of Django models API

Posted by on Aug 1, 2008 in django, Python | 0 comments

If you’ve ever used Twisted framework and got through the first a bit hard learning curve, you most likely fell in love with it.
And if you’ve every used Django you most likely thought — isn’t there a way for it to run faster and in non-blocking fashion — especially if you want to write a web application that integrates other protocols.
One major block on the road is the DB models API which I’ll focus on now.

So let’s say you’re considering to use Django’s models in Twisted application.
Of course this does not automagically makes your code non-blocking. Just allows your blocking DB code to run without affecting Twisted’s reactor (too much). Be careful not to defer to thread too often!

from twisted.internet import reactor, threads
from django.core.management import setup_environ
import settings
import string 

setup_environ(settings)

from foo import models

def getUser(user):
    print "Hello %s %s" % (user.first_name, user.last_name)

def handleError(e):
    print "Error %s" % str(e)

deferred = threads.deferToThread(models.User.objects.get, username='yazzgoth')
deferred.addCallback(getUser)
deferred.addErrback(handleError)
reactor.run()
Read More