简体   繁体   English

Django Celery和多个数据库(Celery,Django和RabbitMQ)

[英]Django Celery and multiple databases (Celery, Django and RabbitMQ)

Is it possible to set a different database to be used with Django Celery? 是否可以设置要与Django Celery一起使用的其他数据库?

I have a project with multiple databases in configuration and don't want Django Celery to use the default one. 我有一个配置中有多个数据库的项目,并且不希望Django Celery使用默认数据库。

I will be nice if I can still use django celery admin pages and read results stored in this different database :) 如果我仍然可以使用django celery管理页面并读取存储在此不同数据库中的结果,我会很高兴的:)

yes you can. 是的你可以。

first: you can set-up a two databases and specify second one explicitly in for the celery tasks (eg obj.save(using='second') ) 首先:您可以建立两个数据库,并为芹菜任务显式指定第二个数据库(例如obj.save(using='second')

or create second settings.py which will be used for the celery: 或创建第二个settings.py将用于芹菜:

./manage.py celeryd --settings_second

It should be possible to set up a separate database for the django-celery models using Django database routers: 应该可以使用Django数据库路由器为django-celery模型建立一个单独的数据库:

https://docs.djangoproject.com/en/1.4/topics/db/multi-db/#automatic-database-routing https://docs.djangoproject.com/en/1.4/topics/db/multi-db/#automatic-database-routing

I haven't tested this specifically with django-celery, but if it doesn't work for some reason, then it's a bug in django-celery (or Django itself) that should be fixed. 我尚未使用django-celery专门测试过此功能,但是如果由于某种原因它无法正常工作,则应该修复django-celery(或Django本身)中的错误。

Your router would look something like this: 您的路由器看起来像这样:

class CeleryRouter(object):
    "Route Celery models to separate DB."
    APPS = (
        'django',  # Models from kombu.transport.django, if you're using Django as a message transport.
        'djcelery',
    )
    DB_ALIAS = 'celery'

    def db_for_read(self, model, **hints):
        if model._meta.app_label in self.APPS:
            return self.DB_ALIAS
        return None

    def db_for_write(self, model, **hints):
        if model._meta.app_label in self.APPS:
            return self.DB_ALIAS
        return None

    def allow_relation(self, obj1, obj2, **hints):
        if (obj1._meta.app_label in self.APPS and
            obj2._meta.app_label in self.APPS):
            return True
        return None

    def allow_syncdb(self, db, model):
        if db == self.DB_ALIAS:
            # Only put models from APPS into Celery table (and south for
            # migrations).
            return model._meta.app_label in self.APPS + ('south',)
        elif model._meta.app_label in self.APPS:
            # Don't put Celery models anywhere else.
            return False
        return None

Then add this to your settings: 然后将其添加到您的设置中:

DATABASE_ROUTERS = ['path.to.CeleryRouter']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM