django预先计算并缓存视图

Col*_*ole 6 python django

这可能是一个python问题.这是一个肯定的诺贝尔人.

客户端请求计算密集型页面[第1页]并最终请求第二个计算密集型页面[第2页],可以计算第1页请求已知的实例.我不希望在提供第1页之前计算每组数据,因为它会显着降低初始响应的性能.

我想在客户端读取第1页时计算第2页的值.客户端也可能会点击某些按钮,这些按钮会导致响应提供不同的第1页数据视图,但不需要进行密集计算.最终但不一定立即,客户端将要求第2页,我希望能够以预先呈现的响应进行响应.

我该怎么做呢?

csi*_*hok 7

正如评论中所提到的,听起来你需要使用异步后台任务处理这个问题,将结果保存在Django低级缓存中.我个人会将celery用于任务队列.

基本上,在请求第一页之后,您将添加一个异步任务来启动页面2计算,将结果存储在缓存中.因此,当请求页面2时,您检查缓存中的预呈现响应,如果它不存在,您可以同步计算该值.

所以,你的代码看起来像这样(任务将在你的应用程序的task.py文件中,但这应该给你一个大致的想法):

from celery import task
from django.core.cache import cache

def page_two_calculation(arg1, arg2):
    return arg1 + arg2

@task
def page_two_task(arg1, arg2):
    result = page_two_calculation(arg1, arg2)
    cache_key = "page-two-%s-%s" (arg1, arg2)
    cache.set(cache_key, result)

def page_one(request, arg1, arg2):

    # Start the page two task
    page_two_task.delay(arg1, arg2)

    # Return the page one response
    return HttpResponse('page one')

def page_two(request, arg1, arg2)
    cache_key = "page-two-%s-%s" (arg1, arg2)
    result = cache.get(cache_key)
    if result is None:
         # the result will only be None if the page 2 calculation
         # doesn't exist in the cache, in which case we'll have to
         # return the value synchronously.
         result = page_two_calculation(arg1, arg2)
    return result
Run Code Online (Sandbox Code Playgroud)