我有一个处理上传文件的 Django 视图,当它被重复调用时,我们总是会遇到内存溢出错误。(我们在 Heroku 上,所以每个 web dyno 有 512mb 的内存)。
内存溢出错误表明每次调用都会根据文件大小增加内存使用量,并且内存使用量永远不会下降。我认为服务器将图像读入内存以将其保存到 Django 模型中,但完成后永远不会释放内存。
我认为必须有对函数返回后持续存在的图像的引用,以防止图像被垃圾收集。但我想不出那可能是什么。
这是代码的简化版本,我对其进行了测试以确保它具有相同的问题:
def simplified_add_image(request, biz_id):
if request.is_ajax():
# the file is stored raw in the request
newBI = NewBusinessImage(business_id=biz_id, name=request.GET.get("name"), primary_image=True)
newBI.id = uuid.uuid4()
newBI.save()
uniquename = biz_id + ".." + get_a_uuid() + ".jpg"
newBI.original_image.save(uniquename, ContentFile(request.read()))
# this starts a series of tasks to process the image into various sizes.
# don't think it's the problem because it runs on a separate server, and the
# web server is the one that goes over memory
tasks.image_meta_task.delay(uniquename, newBI.id)
return StockJSONResponse(request, {
"success" : True,
})
我真的很感激任何帮助。非常感谢!
粘土
以下是评论中要求的其他信息:
我们将文件存储在 AmazonS3 上:
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
STATIC_URL = 'https://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME
from S3 import CallingFormat
AWS_CALLING_FORMAT = CallingFormat.SUBDOMAIN
这是 NewBusinessImage 模型
class NewBusinessImage(models.Model):
id = UUIDField(auto=True,primary_key=True,version=4, default=uuid.uuid4())
business = models.ForeignKey('Business')
name = models.CharField(max_length=100)
original_image = models.ImageField(upload_to='photos/originals/')
thumbnail = models.ImageField(upload_to='photos/thumbnails/')
display_image = models.ImageField(upload_to='photos/displays/')
enlarged_image = models.ImageField(upload_to='photos/enlarged/')
num_views = models.PositiveIntegerField(editable=False, default=0)
primary_image = models.BooleanField(default=False)