【问题标题】:Upload an image from Django shell从 Django shell 上传图像
【发布时间】:2014-08-31 03:53:49
【问题描述】:

我需要将一堆图像导入 Django 应用程序。我正在 shell 中进行测试,但在尝试保存图像时无法克服此错误:

File "/lib/python3.3/codecs.py", line 301, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final) 
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: 
invalid start byte

型号:

import uuid
from django.db import models
from taggit.managers import TaggableManager
import os

def generate_filename(instance, filename):
    f, ext = os.path.splitext(filename)
    name = uuid.uuid4().hex
    return 'images/%s%s' % (name, ext)

class StudyImage(models.Model):

    pic = models.ImageField(upload_to=generate_filename)
    upload_date = models.DateTimeField(auto_now_add=True)
    tags = TaggableManager()

解决错误的步骤:

打开一个 django shell。

import uuid
import os
from app import models

p = File(open('/home/image001.png', 'r'))
a = models.StudyImage(pic=p)
a.pic.save('test.jpg',p)

这给出了上面的错误。我无法弄清楚为什么图像会出现 unicodecodeerror ......我到此为止指的是"Upload" a file from django shell

更多细节:

Django 1.7、Python 3.3

完整的追溯:

Traceback (most recent call last):<br>
File "<input>", line 1, in <module><br>
File "/home/s/Pycharm/flf/venv/lib/python3.3/site-
    packages/django/db/models/fields/files.py", line 89, in save
self.name = self.storage.save(name, content)
File "/home/s/Pycharm/flf/venv/lib/python3.3/site-
    packages/django/core/files/storage.py", line 51, in save
    name = self._save(name, content)
File "/home/s/Pycharm/flf/venv/lib/python3.3/site-
    packages/django/core/files/storage.py", line 224, in _save
    for chunk in content.chunks():
File "/home/s/Pycharm/flf/venv/lib/python3.3/site-packages/django/core/files/base.py",
    line 77, in chunks
    data = self.read(chunk_size)
File "/home/s/Pycharm/flf/venv/lib/python3.3/codecs.py", line 301, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
    UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

【问题讨论】:

  • 你试过把p = File(open('/home/image001.png', 'r'))换成p = File(open('/home/image001.png', 'rb'))吗?
  • 我没有,很遗憾!这就是问题所在。似乎 'r' 和 'rb' 设置在 Python 3 中的工作方式与在 2 - stackoverflow.com/questions/9644110/… 中不同。 @MBrizzle - 如果您将此添加为我会接受的答案。谢谢。
  • 是的,rb 标志告诉文件句柄将文件作为二进制数据读取,这是您在打开图像、可执行文件等时会执行的操作。

标签: python django file shell


【解决方案1】:

我以前被这个咬过,所以我感觉到你 - 但根据我的评论:在 File() 调用中将 'r' 替换为 'rb',它应该可以正常工作。

我还应该补充一点,对于那些后来得到这个答案的人,这是 Python3 特有的问题。请查看史蒂夫评论中的 SO 链接,以更全面地解释 p2 和 p3 之间File() 的区别。

【讨论】:

  • 像魅力一样工作。谢谢您,好心的先生或女士!
猜你喜欢
  • 1970-01-01
  • 2020-03-02
  • 2011-11-06
  • 2014-10-01
  • 2015-02-22
  • 2010-11-16
  • 2016-02-23
  • 2018-06-14
  • 1970-01-01
相关资源
最近更新 更多