正如评论中提到的,听起来您需要使用异步后台任务来处理这个问题,将结果保存在Django 低级缓存中。我个人会使用芹菜作为任务队列。
基本上,在请求第一页后,您将添加一个异步任务来启动第二页计算,并将结果存储在缓存中。因此,当请求第 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