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.
As in my previous post you’ll have to prepare the environment to access the models, then use Twisted’s threaded deferred to make it non-blocking.

Python [Show Plain Code]:
  1. from twisted.internet import reactor, threads
  2. from django.core.management import setup_environ
  3. import settings
  4. import string
  5. setup_environ(settings)
  6. from foo import models
  7.  
  8. def getUser(user):
  9.    print "Hello %s %s"%(user.first_name, user.last_name)
  10.  
  11. def handleError(e):
  12.    print "Error "+str(e)
  13.  
  14. deferred = threads.deferToThread(models.User.objects.get, username=‘yazzgoth’)
  15. deferred.addCallback(getUser)
  16. deferred.addErrback(handleError)
  17. reactor.run()

Leave a Reply