如何在Django中使用Kombu和芹菜创建一个点击计数器

时间:2015-11-11 17:31:49

标签: python django django-celery kombu

我正在尝试使用Django中的Kombu和Celery自定义this tutorial来创建点击计数器。该教程解释了如何为url执行此操作,但我想要做的是创建Click模型,将帖子定义为P-000324字段,然后每当有人查看该帖子时,我会调用该帖子的增量点击

我有两个问题: 第一个是我应该在视图中放置函数调用,因为我使用的是通用视图(见下文)? 第二个是我应该如何使用ForeignKey?我是否将对象写入函数?

models.py

message

messaging.py

class ClickManager(models.Manager):

    def increment_clicks(self, for_url, increment_by=1):
        click, created = self.get_or_create(url=for_url, defaults={"click_count": increment_by})
        if not created:
            click.click_count += increment_by
            click.save()

        return click.click_count

class Click(models.Model):
    obj = models.ForeignKey(Post)
    click_count = models.PositiveIntegerField(_(u"click_count"), default=0)

    objects = ClickManager()

    def __unicode__(self):
        return self.obj

views.py

def send_increment_clicks(obj):
    connection = establish_connection()
    publisher = Publisher(connection=connection, exchange="clicks", routing_key="increment_click", exchange_type="direct")

    publisher.send(obj)

    publisher.close()
    connection.close()


def process_clicks():
    connection = establish_connection()
    consumer = Consumer(connection=connection, queue="clicks", exchange="clicks", routing_key="increment_click", exchange_type="direct")

    clicks_for_url = {}
    message_for_url = {}

    for message in consumer.iterqueue():
        obj = message.body
        clicks_for_url[obj]= clicks_for_url.get(obj, 0) + 1
        if obj in messages_for_url:
            messages_for_url[obj].append(message)
        else:
            messages_for_url[obj] = [message]

    for obj, click_count in clicks_for_url.items():
        Click.objects.increment_click(obj, click_count)
        [message.ack() for message in messages_for_url[obj]]

    consumer.close()
    connection.close()

0 个答案:

没有答案