我已经为 Django 创建了一个 ajax 文件上传器,但是每个上传的文件都占用了一大块内存(30-80 mb),而且似乎并没有放过它。
我们在 Heroku 上,它为每个测功机分配 512mb 的内存,所以我很快就开始遇到内存过剩的错误。
这是处理请求的 Django 视图代码:
if request.is_ajax():
# the file is stored raw in the request
upload = request
is_raw = True
try:
filename = request.GET[ 'add_image' ]
except KeyError:
return HttpResponseBadRequest( "AJAX request not valid" )
(fileBaseName, fileExtension)=os.path.splitext(filename)
uniquename = biz_id + "__" + get_a_uuid() + fileExtension
saved = save_upload(upload, uniquename, biz)
这是 save_upload 代码:
try:
#BusinessImage is my Django model. It uses django-imagekit to processs
#the raw uploaded image into three sizes (plus the original)
bi = BusinessImage(name=uploaded.GET.get("name"), business=biz)
if not BusinessImage.objects.filter(business=biz).exists():
bi.primary_image = True
bi.original_image.save(filename,ContentFile(uploaded.read()))
except IOError:
# could not open the file most likely
return False
finally:
uploaded.close()
return True
这段代码改编自这篇文章(感谢 Alex Kuhl 和 Thunder Rabbit)。
我在想内存问题可能与 django-imagekit 有关,或者我可能没有正确关闭文件,但我不确定。我真的很感激任何帮助。
谢谢!
粘土