Django / Python / PIL / sorl-批量生成缩略图 - 内存错误

发布于 2024-08-13 02:02:17 字数 705 浏览 7 评论 0原文

我正在尝试使用 sorl-thumbnail 对于我的 Django 应用程序。我使用 ImageWithThumbnailsFieldFile 迭代所有 django 对象,然后调用其generate_thumbnails() 函数。

这工作得很好,除了在几百次迭代之后,我耗尽了内存并且我的循环因“内存错误”而崩溃。由于 sorl-thumbnail 使用 PIL 来生成缩略图,因此 PIL 似乎不会返回生成缩略图时使用的所有内存。

有人如何避免这个问题,例如通过强制 PIL 返回它不再需要的内存吗?

我的代码看起来像这样:

all = Picture.objects.all()
for i in all:
    i.image.generate_thumbnails()

函数generate-thumbnail开始 此处,第 129 行。

提前感谢您的任何建议!

马丁

I'm trying to bulk generate 4 thumnails for each of around 40k images with sorl-thumbnail for my django app. I iterate through all django objects with an ImageWithThumbnailsFieldFile, and then call its generate_thumbnails() function.

This works fine, except that after a few hundred iterations, I run out of memory and my loop crashes with 'memory error'. Since sorl-thumbnail uses PIL to generate thumbs, it seems to be that PIL doesn't return all of the memory it used when generated a thumb.

Does anybody how to avoid this problem, e.g. by forcing PIL to return the memory it no longer needs?

my code simply looks like this:

all = Picture.objects.all()
for i in all:
    i.image.generate_thumbnails()

The function generate-thumbnail starts here, line 129.

Thanks in advance for any advice!

Martin

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

掩于岁月 2024-08-20 02:02:17

您的问题与 Django 在循环查询集时如何缓存查询集的结果有关。 Django 将所有对象保留在内存中,以便下次迭代相同的查询集时,无需再次访问数据库来获取所有数据。

您需要做的是使用 iterator()方法。所以:

all = Picture.objects.all().iterator()
for i in all:
    i.image.generate_thumbnails()

Your problem relates to how Django caches the results of a queryset as you loop through them. Django keeps all the objects in memory so that next time you iterate through the same queryset you don't have to hit the database again to get all the data.

What you need to do is use the iterator() method. So:

all = Picture.objects.all().iterator()
for i in all:
    i.image.generate_thumbnails()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文