我在 Heroku 中運行一個 Django 應用程序,它處理來自用戶的多個圖像上傳并將它們存儲到 Amazon S3。問題是這個過程的執行通常需要30s以上(Heroku的時間執行限制)。我對其進行了測試,需要較長時間的行是將圖像文件保存在 ImageField 中的行。這樣做是因為必須通過 ProcessImageFile() 裁剪和處理圖像。不過這個功能用的時間不是很長,而是保存方法本身,可能是因為它在保存文件的同時將文件一個一個地存儲在S3中。這是視圖(省略了不相關的行): @login_required def image_create(request): if request.method == 'POST': images = request.FILES.getlist("files") crop_points = json.loads( request.POST.get('crop_points')) #Validation of inputs in the form: images and other fields if len(images) < 3 : return JsonResponse({'val_result': 'min_error'}) if len(images) > 12: return JsonResponse({'val_result': 'max_error'}) #We Create the gallery, iterate over the images provided by the form, validate, insert custom fields and save them in bulk associating it to the gallery. with transaction.atomic(): new_items = [] gallery = Gallery.objects.create( user=request.user ) for i, img_file in enumerate(images): new_item = Image() new_item.user = request.user #-----THIS IS THE PART WHICH TAKES MOST OF THE VIEW PROCESSING TIME: IT IS NOT THE ProcessImageFile FUNCTION, BUT THE SAVE METHOD ITSELF new_item.image.save( 'img'+ str(i) + '.jpg', content = ProcessImageFile(img_file, crop_points), save=False )我已經嘗試使用 Celery 在單獨的任務中處理文件上傳,但這里的問題是將請求或圖像文件傳遞給任務,因為它們必須被序列化。無論如何,我想這里有一些效率低下的地方,這個簡單的視圖不應該花費超過 30 秒的時間在 S3 中上傳五張圖像并返回響應。也許解決方案是將所有圖像一起批量發送到 S3,或者以其他方式保存它們,我不知道。
添加回答
舉報
0/150
提交
取消