【问题标题】:seek() takes 2 positional arguments but 3 were givenseek() 接受 2 个位置参数,但给出了 3 个
【发布时间】:2020-02-07 05:17:55
【问题描述】:

我正在将图像上传到内存,然后我想将其保存到 imageField()。

我使用 django-storages 将文件从 image/fileField() 上传到 AWS S3。

我将图像下载到内存中:

        r = requests.get(url, headers=header)
        image = Image.open(BytesIO(r.content))
        image_in_memory = InMemoryUploadedFile(image, None, "foo.png",  'image/png', image.size, None)
        image_in_memory_file = image_in_memory.file

一些验证:

print(type(image_in_memory))

---
<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>

当我保存这个时:

my_object.cover.save(name="foo.png", content=image_in_memory)

Django 产生这个错误:

web_1      |     link.cover.save(name="foo.png", content=image_in_memory)
web_1      |   File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/files.py", line 87, in save
web_1      |     self.name = self.storage.save(name, content, max_length=self.field.max_length)
web_1      |   File "/usr/local/lib/python3.7/site-packages/django/core/files/storage.py", line 52, in save
web_1      |     return self._save(name, content)
web_1      |   File "/usr/local/lib/python3.7/site-packages/storages/backends/s3boto3.py", line 491, in _save
web_1      |     self._save_content(obj, content, parameters=parameters)
web_1      |   File "/usr/local/lib/python3.7/site-packages/storages/backends/s3boto3.py", line 505, in _save_content
web_1      |     content.seek(0, os.SEEK_SET)
web_1      | TypeError: seek() takes 2 positional arguments but 3 were given

你发现问题了吗?

【问题讨论】:

  • 也许你应该使用content=image_in_memory_file?
  • 我也试过了,同样的错误:seek() takes 2 positional arguments but 3 were given

标签: python django amazon-s3 django-storage


【解决方案1】:

出于某种原因,您将文件包装在 Pillow Image 类中。 Image seek 方法适用于图像序列,正如错误所解释的,它采用两个位置参数。

不要将其包装为图像:

r = requests.get(url, headers=header)
image = BytesIO(r.content)
image_in_memory = InMemoryUploadedFile(image, None, "foo.png",  'image/png', len(r.content), None)

还请注意,还有一个更简单的类 SimpleUploadedFile,它只需要名称和内容,这可能就是您需要的:

r = requests.get(url, headers=header)
image_in_memory = SimpleUploadedFile("foo.png", r.content, 'image/png')

【讨论】:

  • 有同样的问题。我需要包装图像以调整它的大小。如何保存调整大小的图像?
猜你喜欢
  • 2022-01-17
  • 2019-09-21
  • 2019-07-19
  • 2021-02-02
  • 2017-03-14
  • 2014-09-07
  • 1970-01-01
  • 1970-01-01
  • 2022-12-12
相关资源
最近更新 更多