使用 django-celery 时如何创建单个 class 对象?

How to create single class object when using django-celery?

我正在使用 celery beat schedule 在午夜自动重置属性。之后我还想使用 firebase 向所有相关用户发送通知。所以,我写了下面的代码。

def send_notification(reg_ids, data_message):

    push_service = FCMNotification(api_key=fcm_config['GCM_API_KEY'])
    push_service.multiple_devices_data_message(registration_ids=reg_ids, data_message=message)


@shared_task 
def reset_daily_count():

    try:
        User.objects.all().update(daily_attempts=3)
    except Exception as e:
        logger.debug(e)
    else:
        send_notification(reg_ids, data_message)

但是这段代码会创建FCMNotification对象,每次我都会调用它。我想要的是创建一个对象并在需要时从某个地方访问它,即使是其他芹菜任务,不仅是周期性任务,还有正常任务。我该怎么做?

只需在您定义的地方创建一个对象 class 然后将其导入任何您想要的地方。

class FCMNotification:
    pass
    # daclaration


push_service = FCMNotification(api_key=fcm_config['GCM_API_KEY'])

您可以在 celery 任务中使用 push_service 以及像这样的普通代码。

from <PATH> import push_service