Django:上载的文件没有被垃圾回收,导致内存问题

时间:2012-08-09 18:43:35

标签: python django memory file-upload heroku

我有一个处理上传文件的Django视图,当它被重复调用时,我们总会遇到内存错误。 (我们在Heroku上,所以我们每个网络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)

1 个答案:

答案 0 :(得分:0)

根据Django文档,它附带了2个文件上传处理程序。内存和临时文件处理程序(Link to docs)

如果将设置FILE_UPLOAD_HANDLERS设置配置为仅包含" django.core.files.uploadhandler.TemporaryFileUploadHandler"它永远不应该将文件保存到内存中,并且技术上永远不会导致您当前面临的内存问题。

另一种选择是将FILE_UPLOAD_MAX_MEMORY_SIZE设置为少量,以使上传直接进入磁盘。