我在 Django 中有一個簡單的 ListCreateApiView 類,例如:
class Test(ListCreateApiView):
def list(self, request, *args, **kwargs):
""" Some code which is creating excel file with openpyxl and send as response """
return excel_file
問題是,當用戶發送請求以獲取 excel_file 時,他必須等待 5-10 分鐘,直到檔案回傳。用戶無法訪問其他網址,直到檔案無法下載(我的資料庫中有 10k 個物件)
那么,如何在這里添加異步?我希望在形成檔案時,一個人可以關注應用程式的其他鏈接。
非常感謝!
uj5u.com熱心網友回復:
django 的異步有些麻煩,在cpu密集型任務中異步呼叫對你沒有幫助,你最好使用像celery這樣的分布式任務佇列
它將允許您在另一個執行緒中處理如此繁重的任務(即生成 excel),而不會中斷主 django 執行緒。按照與 django 集成的指南。
安裝和配置后,創建一個任務并在用戶到達端點時觸發它:例如:
# tasks.py
from celery import shared_task
@shared_task
def generate_excel(*args, **kwargs):
...
# views.py
from tasks import generate_excel
class Test(ListCreateApiView):
def list(self, request, *args, **kwargs):
generate_excel.delay()
return Response()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/498348.html
