如何在Celery任务中更改数据库架构?

时间:2019-06-08 08:01:22

标签: python django celery

我有一个可以根据子域更改数据库架构的中间件:

def tenant_schema_from_request(request):
    hostname = hostname_from_request(request)
    tenants_map = get_tenants_map()
    return tenants_map.get(hostname)

def set_tenant_schema_for_request(request):
    schema = tenant_schema_from_request(request)
    with connection.cursor() as cursor:
        cursor.execute("SET search_path to {}".format(schema))

class TenantMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        set_tenant_schema_for_request(request)
        response = self.get_response(request)
        return response

但是如何在Celery任务中更改数据库架构?

tasks.py

@shared_task
def send_notification_task(user_id):
    user = User.objects.get(pk=user_id)
    ...

2 个答案:

答案 0 :(得分:1)

我认为您正在寻找.using

Author.objects.using('default').all()

希望这会有所帮助!

答案 1 :(得分:0)

老问题,但我遇到了完全相同的问题,并找到了解决方案。分享它,以防其他人需要它。

在任务运行之前,您应该使用celery task_prerun信号切换活动模式。

下面是一个在任务运行之前将当前模式切换到公共模式的示例。

from celery.signals import task_prerun
from django.db import connection

# ensure the task always runs on the public schema
@task_prerun.connect(sender=send_notification_task)
def activate_public_schema(sender, **kwargs):
    connection.schema_name = 'public'

@shared_task
def send_notification_task(user_id):
    user = User.objects.get(pk=user_id)
    ...