我有一个任务.py包含Task的子类。 根据docs,每个任务只实例化一次基类。在
但这只适用于相同的任务方法。调用不同的任务将创建一个新实例。所以我不能通过使用create_session
创建的get_sessions
访问会话。我怎么可能只有一个实例在不同的任务之间共享?在
class AuthentificationTask(Task):
connections = {}
def login(self, user, password, server):
if not user in self.connections:
self.connections = {user: ServerConnection(verbose=True)}
# from celery.contrib import rdb
# rdb.set_trace()
self.connections[user].login(user=user, password=password, server=server)
@task(bind=True, max_retries=1, queue='test', base=AuthentificationTask)
def create_session(self, user, password, server):
self.login(user, password, server)
@task(bind=True, max_retries=1, queue='test', base=AuthentificationTask)
def get_sessions(self, user, password, server):
return self.connections[user].sessions
通过将})替换为
connections
作为AuthentificationTask
上的类变量,您就走对了。这使得它可以作为类本身的属性来使用(例如,作为AuthentificationTask.connections
)。当您在login方法中引用self.connections
时,我相信Python正在寻找一个实例变量connections
,而不是同名的类变量。对于所需的行为,将self.connections
(在login
和{AuthentificationTask.connections
。在为Celery应用程序设置
task_cls
参数,如下所示:在本例中,所有任务都将使用自定义类作为默认值。在
似乎这是我的网站上的一个问题,因为每次重新初始化
self.connections
。在在进一步的测试中,
base
只为所有(不同)任务实例化一次。感谢@Danila Ganchar提出了另一种方法。我试试看!在相关问题 更多 >
编程相关推荐