screeley.com

Django Daemon Command Extension

June7

Recently I started to move Cubby Scott away from a cron and towards a queue. It's hard to be real time when you wake up a cron job once every 3 minutes. Lame. I'm also in the process of adding screenshots and content retrieval. Both take a good amount of time to process. The queue part was easy after reading Rabbits and Warrens and Working with Python and RabbitMQ. The problem came when I started working on the consumer, no one ever talks about the consumer. Well I'm going to give the consumer some love.

The consumer should be a daemon, but what's the best way to do that? It would be nice if I could just use Django's built in management functions rather than having one off scripts. i.e:

python manage.py linkconsumer

I would run that once when I started up the server and be good to go. It turned out to be pretty easy with python-daemon. I threw together a quick class to handle it and you can get a copy of the DaemonCommand here. All it really does is create an interface for a daemon context and open it. When subclassing the DaemonCommand instead of calling handle use handle_daemon.

Carrot is the open source project that ties the two together, but was a little too complex. So for the purpose of keeping it simple stupid, I used Nathan Borror's Flopsy. Dead simple way to communicate with a queue.

If we put that together we accomplish our goal in 20 lines of code.

from daemonextension import DaemonCommand
from django.conf import settings
import os

class Command(DaemonCommand):
    #Declare Daemon std.
    stdout = os.path.join(settings.DIRNAME, "log/cubbyscott.out")
    stderr = os.path.join(settings.DIRNAME, "log/cubbyscott.err")
    pidfile = os.path.join(settings.DIRNAME, "pid/cb_link.err")
    
    def handle_daemon(self, *args, **options):
        from flopsy import Connection, Consumer
        consumer = Consumer(connection=Connection())
        consumer.declare(queue='links', 
                         exchange='cubbyscott', 
                         routing_key='importer', auto_delete=False)
        
        def message_callback(message):
            print 'Recieved: ' + message.body
            consumer.channel.basic_ack(message.delivery_tag)
        
        consumer.register(message_callback)
        
        consumer.wait()

Comments

Have you seen celery? http://pypi.python.org/pypi/celery

What do you think is complex in carrot? it's basically the same interface.

@Ask. celery looks awesome. I'll be playing with that today.

My issue with carrot was declaring queues and the lack of documentation. I don't have a lot of patience when it comes to that.

celery looks like it solves both those problems. Send me an email, would like to talk to you about it. sean@screeley.com

@sean I don't know if you've followed carrot recently, but after Nathan's blog post we've started documenting carrot, and it's really come a long way. See: http://ask.github.com/carrot/index.html Any comments/critique on the documentation is more than welcome.

carrot was originally just a part of celery, but seems to be useful on its own. Of course, py-amqplib is really what binds all this together, but I feel we need a common, tested, library, solving common messaging tasks as well.

I'll send you an e-mail.

по моему мнению: восхитительно. а82ч

uh.. strange ..

Post Your Comment

I'm a developer out of Boston MA and I work for a consulting firm specializing in open source technologies.

This space will deal with the work I've participated in using the Django framework to build applications for enterprise clients.

Finally, I hate the word blog and Drupal.

Ruminations

  • "А интересно, сам автор читает комментарии к этому сообщению. Или мы тут сами для себя пишем? :)"
    at 4:58a.m. March 9, 2010 | permalink

  • "Прошу прощения за оффтопик. Вы продаете сквозные ссылки с сайта? Если да, свяжитесь со мной, плз!"
    at 8:06p.m. March 8, 2010 | permalink

  • "Об этом уже писал кто-то из моих ЖЖ-френдов :("
    at 10:29a.m. March 8, 2010 | permalink

  • "У Вас долго загружается блог - видимо, хостинг плоховат"
    at 9:41p.m. March 6, 2010 | permalink

  • "I just discovered <a href=http://bit.ly/bMGrYw>SatelliteTV</a> on my PC! Ultra cheap at only $50 once off to get the software and an account on the Internet. ..."
    at 5:20p.m. March 4, 2010 | permalink

  • "Логотип мне нравится:)"
    at 8:47a.m. March 4, 2010 | permalink

  • "Девушки из твоих грёз на твоём рабочем столе. 1.Полностью бесплатно 2.100% безопасность вашего ПК 3.Новые девушки каждый день <a href=http://blogs.mail.ru/mail/erorulez/6605707A18ACC7D6.html>смотреть стриптиз бесплатно</a> http://blogs.mail.ru/mail/erorulez/6605707A18ACC7D6.html эгоистка стриптиз ..."
    at 5:08a.m. March 4, 2010 | permalink

  • "uh.. strange .."
    at 11:54p.m. March 3, 2010 | permalink

  • "Hi guys, I know this might be a bit off topic but seeing that a bunch of you own websites, where would the best place ..."
    at 11:12p.m. March 3, 2010 | permalink

  • "Thanks for this, unbelievable our developer has a robots no follow tag on our site, no wonder it wasn't being found by the search engines ..."
    at 7:40a.m. March 2, 2010 | permalink

  • "В Вашей RSS нельзя получать полные тексты записей, что ли?"
    at 9:37p.m. March 1, 2010 | permalink

  • "Hello, We are representing <a href="http://www.keepingmyhair.com/hair-cloning-a-resume">Hair Loss news</a>. We manage plenty of web sites, and we found your website trought the net. We are asking ..."
    at 12:58a.m. Feb. 28, 2010 | permalink