gpt4 book ai didi

django - 使用 celery 异步执行 Django 应用程序的任务

转载 作者:可可西里 更新时间:2023-11-01 11:34:19 25 4
gpt4 key购买 nike

在我维护的 Django 应用程序中,用户登录并相互交换消息,论坛风格。在任何给定的时间点,我通过检查在过去 5 分钟内登录了 session 对象的人来显示谁在线。为此,我使用了 Django 插件 user_sessions ,这允许像常规 ORM 一样操作 session 。

我实现这个的代码是这样的:

class WhoseOnlineView(ListView):
model = Session
template_name = "whose_online.html"

def get_queryset(self):
unique_user_sessions = Session.objects.filter(last_activity__gte=(timezone.now()-timedelta(minutes=5))).only('user').distinct('user')
users = [session.user for session in unique_user_sessions]
users = [user for user in users if user is not None] #sanitizing None values
return users

该网站的用户(和功能)有了很大的增长,根据 newrelic,这个特定的 View 在我所有的 View 中花费了最多的时间。

我想我应该将整个任务移到异步完成。我在生产服务器上的 supervisord 下启动并运行了 celery(使用 redis 作为消息代理)。

这可能是一个周期性任务,每 60 秒执行一次。但似乎要让它工作,我需要在数据库(或缓存)中保存结果,以便用户可以看到保存的结果,直到下一次处理其在线列表.

有人可以给我一个说明性的例子来说明如何完成这个吗?我遇到的主要问题是如何保存(或缓存)在下一个周期性任务开始之前向用户显示的结果。

最佳答案

你可以这样做:

首先,编写 celery 任务来找出登录用户,例如

# fooapp.tasks

@shared_task
def whoseonline():
unique_user_sessions = Session.objects.filter(last_activity__gte=(timezone.now()-timedelta(minutes=5))).only('user').distinct('user')
users = [session.user for session in unique_user_sessions users = [user for user in users if user is not None] #sanitizing None values
# save the users to the cache
cache.set('online_users', users, 70) # expiring in 70 seconds

并设置任务以便运行一定的时间,例如60 秒,添加这个:

# settings.py

CELERYBEAT_SCHEDULE = {
'whoseonline': {
'task': 'fooapp.tasks.whoseonline',
'schedule': timedelta(seconds=60), # execute every 60 seconds
'args': (),
},
}

到您的设置。然后,在你看来,你只需要做

class WhoseOnlineView(ListView):
model = Session
template_name = "whose_online.html"

def get_queryset(self):
# take the values from the cache
return cache.get('online_users')

Here有关缓存和 here 的更多信息更多关于 celery 。

您还应该记住,缓存时间到期(示例中为 70 秒)应该大于您将用于 celery 任务的预定时间(示例中为 60 秒),以便 View 始终有一些东西显示。

关于django - 使用 celery 异步执行 Django 应用程序的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37444472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com