让可重用任务在具有一台 celery 服务器和 3k+ 的设置中工作django 站点,每个站点都有自己的数据库

发布于 2024-12-13 11:40:16 字数 214 浏览 4 评论 0原文

问题是:我有一台 celery 服务器和 3k+ django 站点,每个站点都有自己的数据库。可以动态添加新站点(和数据库)。

我正在编写需要通过公共 celery 服务器为每个站点运行的 celery 任务。该代码位于可重用的应用程序中,因此不应以将其与此特定设置联系在一起的方式编写。

所以。在不修改任务代码以适应我的确切设置的情况下,如何确保任务在运行时连接到正确的数据库?

Here's the problem: I have one celery server and 3k+ django sites, each with its own database. New sites (and databases) can be added dynamically.

I'm writing celery tasks which need to be run for each site, through the common celery server. The code is in an app which is meant to be reusable, so it shouldn't be written in a way that ties it to this particular setup.

So. Without mangling the task code to fit my exact setup, how can I make sure that the tasks connect to the correct database when they run?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谁的新欢旧爱 2024-12-20 11:40:16

由于 Django 的固有限制,这很难实现:设置是全局的。因此,除非所有应用程序共享相同的设置,否则这将是一个问题。

您可以尝试为每个任务生成新的工作进程并每次创建 django 环境。不要使用 django-celery,而是直接使用 celery 和类似的东西
celeryconfig.py:

from celery import signals
from importlib import import_module

def before_task(task, **kwargs):
    settings_module = task.request.kwargs.pop("settings_module", None)
    if settings_module:
        settings = import_module(settings_module)
        from django.conf import setup_environ
        setup_environ(settings)
signals.task_prerun.connect(before_task)

CELERYD_MAX_TASKS_PER_CHILD = 1

This is hard to accomplish because of an inherent limitation in Django: The settings are global. So unless all the apps shared the same settings, this is going to be a problem.

You could try spawning new worker processes for every task and create the django environment each time. Don't use django-celery, but use celery directly with something like this in
celeryconfig.py:

from celery import signals
from importlib import import_module

def before_task(task, **kwargs):
    settings_module = task.request.kwargs.pop("settings_module", None)
    if settings_module:
        settings = import_module(settings_module)
        from django.conf import setup_environ
        setup_environ(settings)
signals.task_prerun.connect(before_task)

CELERYD_MAX_TASKS_PER_CHILD = 1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文