草庐IT

python - Django 1.5 在持久化上传文件时引发 UnicodeDecodeError

coder 2023-10-10 原文

当我将项目的 django 版本更新到 1.5.x 时,这个问题开始出现。

我的问题是,当我使用 mysql 作为后端并上传文件并尝试将该文件的 block 保存到另一个模型时,我得到了 UnicodeDecodeError。

在 django 1.4.x 中没有错误抛出并且相关模型被持久化。

要重新创建的示例项目: https://github.com/imtapps/fileuploaderror

模型.py

from django.db import models

class LongBlob(models.Field):
    def db_type(self, connection):
        return "longblob"   

class Document(models.Model):
    document = LongBlob()

class Book(models.Model):
    description = models.CharField(max_length=30)
    document = models.ForeignKey(Document, null=True)

表单.py

from django import forms
from spikeapp.models import Document, Book

class BookForm(forms.ModelForm):
    upload_file = forms.FileField()

    def save(self, *args, **kwargs):
        self.cleaned_data['upload_file'].open()
        data = ''.join([chunk for chunk in self.cleaned_data['upload_file'].chunks()])
        self.cleaned_data['upload_file'].close()
        Document.objects.create(document=data)

    class Meta:
        model = Book
        fields = ('description',)

View .py

from django.views.generic.edit import FormView
from spikeapp.forms import BookForm

class FileView(FormView):
    template_name = 'file.html'
    form_class = BookForm
    success_url = "/"

    def form_valid(self, form):
        form.save()
        return super(FileView, self).form_valid(form)

这是异常(exception)情况:

Traceback:
File "/home/appsdev/.virtualenvs/blobspike/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "/home/appsdev/.virtualenvs/blobspike/local/lib/python2.7/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)
File "/home/appsdev/.virtualenvs/blobspike/local/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
  86.         return handler(request, *args, **kwargs)
File "/home/appsdev/.virtualenvs/blobspike/local/lib/python2.7/site-packages/django/views/generic/edit.py" in post
  165.             return self.form_valid(form)
File "/home/appsdev/Projects/blobspike/spikeapp/views.py" in form_valid
  11.         form.save()
File "/home/appsdev/Projects/blobspike/spikeapp/forms.py" in save
  12.         Document.objects.create(document=data)
File "/home/appsdev/.virtualenvs/blobspike/local/lib/python2.7/site-packages/django/db/models/manager.py" in create
  149.         return self.get_query_set().create(**kwargs)
File "/home/appsdev/.virtualenvs/blobspike/local/lib/python2.7/site-packages/django/db/models/query.py" in create
  416.         obj.save(force_insert=True, using=self.db)
File "/home/appsdev/.virtualenvs/blobspike/local/lib/python2.7/site-packages/django/db/models/base.py" in save
  546.                        force_update=force_update, update_fields=update_fields)
File "/home/appsdev/.virtualenvs/blobspike/local/lib/python2.7/site-packages/django/db/models/base.py" in save_base
  650.                 result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/home/appsdev/.virtualenvs/blobspike/local/lib/python2.7/site-packages/django/db/models/manager.py" in _insert
  215.         return insert_query(self.model, objs, fields, **kwargs)
File "/home/appsdev/.virtualenvs/blobspike/local/lib/python2.7/site-packages/django/db/models/query.py" in insert_query
  1675.     return query.get_compiler(using=using).execute_sql(return_id)
File "/home/appsdev/.virtualenvs/blobspike/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
  937.             cursor.execute(sql, params)
File "/home/appsdev/.virtualenvs/blobspike/local/lib/python2.7/site-packages/django/db/backends/util.py" in execute
  45.             sql = self.db.ops.last_executed_query(self.cursor, sql, params)
File "/home/appsdev/.virtualenvs/blobspike/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py" in last_executed_query
  243.         return cursor._last_executed.decode('utf-8')
File "/home/appsdev/.virtualenvs/blobspike/lib/python2.7/encodings/utf_8.py" in decode
  16.     return codecs.utf_8_decode(input, errors, True)

Exception Type: UnicodeDecodeError at /
Exception Value: 'utf8' codec can't decode byte 0xb5 in position 67: invalid start byte

要复制的版本: MySQLdb-Python = 1.2.4

Django = 1.5.4

最佳答案

您偶然发现了 Django 1.5 中的错误:#19954 Storing of Binary fields leads to Exceptions .

committed fix是用“替换”强制解码最后执行的查询:

return force_text(cursor._last_executed, errors='replace')

您可以编辑 Django 源代码,或应用 monkeypatch:

from django.utils.encoding import force_text
from django.db.backends.mysql.base import DatabaseOperations

def fixed_last_executed_query(self, cursor, sql, params):
    return force_text(cursor._last_executed, errors='replace')

DatabaseOperations.last_executed_query = fixed_last_executed_query

尽早这样做,例如,在您的设置模块或包的顶部。

我不认为补丁被反向移植了;到目前为止它只进入了 1.6 开发线,可能是因为 1.6 添加了一个新的 Binary 字段类型。

关于python - Django 1.5 在持久化上传文件时引发 UnicodeDecodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18923215/

有关python - Django 1.5 在持久化上传文件时引发 UnicodeDecodeError的更多相关文章

  1. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  2. ruby-on-rails - Rails 模型——非持久类成员或属性? - 2

    对于Rails模型,是否可以/建议让一个类的成员不持久保存到数据库中?我想将用户最后选择的类型存储在session变量中。由于我无法从我的模型中设置session变量,我想将值存储在一个“虚拟”类成员中,该成员只是将值传递回Controller。你能有这样的类(class)成员吗? 最佳答案 将非持久属性添加到Rails模型就像任何其他Ruby类一样:classUser扩展解释:在Ruby中,所有实例变量都是私有(private)的,不需要在赋值前定义。attr_accessor创建一个setter和getter方法:classUs

  3. ruby-on-rails - Capybara-webkit 引发 Capybara::Driver::Webkit::WebkitInvalidResponseError - 2

    我在rspec中收到来自webkit驱动程序的以下消息:Capybara::Driver::Webkit::WebkitInvalidResponseError:UnabletoloadURL:http://127.0.0.1:44923/posts几天前它成功了。问题出在save_page方法上。有什么问题吗? 最佳答案 当我的页面出现错误时,我收到过类似的错误消息。您应该通过在测试模式下启动服务器(railss-etest)并自行访问页面来手动检查情况是否如此。 关于ruby-on-

  4. Python 相当于 Perl/Ruby ||= - 2

    这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Pythonconditionalassignmentoperator对于这样一个简单的问题表示歉意,但是谷歌搜索||=并不是很有帮助;)Python中是否有与Ruby和Perl中的||=语句等效的语句?例如:foo="hey"foo||="what"#assignfooifit'sundefined#fooisstill"hey"bar||="yeah"#baris"yeah"另外,类似这样的东西的通用术语是什么?条件分配是我的第一个猜测,但Wikipediapage跟我想的不太一样。

  5. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  6. 华为OD机试用Python实现 -【明明的随机数】 2023Q1A - 2

    华为OD机试题本篇题目:明明的随机数题目输入描述输出描述:示例1输入输出说明代码编写思路最近更新的博客华为od2023|什么是华为od,od薪资待遇,od机试题清单华为OD机试真题大全,用Python解华为机试题|机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为o

  7. python - 如何读取 MIDI 文件、更改其乐器并将其写回? - 2

    我想解析一个已经存在的.mid文件,改变它的乐器,例如从“acousticgrandpiano”到“violin”,然后将它保存回去或作为另一个.mid文件。根据我在文档中看到的内容,该乐器通过program_change或patch_change指令进行了更改,但我找不到任何在已经存在的MIDI文件中执行此操作的库.他们似乎都只支持从头开始创建的MIDI文件。 最佳答案 MIDIpackage会为您完成此操作,但具体方法取决于midi文件的原始内容。一个MIDI文件由一个或多个音轨组成,每个音轨是十六个channel中任何一个上的

  8. 「Python|Selenium|场景案例」如何定位iframe中的元素? - 2

    本文主要介绍在使用Selenium进行自动化测试或者任务时,对于使用了iframe的页面,如何定位iframe中的元素文章目录场景描述解决方案具体代码场景描述当我们在使用Selenium进行自动化测试的时候,可能会遇到一些界面或者窗体是使用HTML的iframe标签进行承载的。对于iframe中的标签,如果直接查找是无法找到的,会抛出没有找到元素的异常。比如近在咫尺的例子就是,CSDN的登录窗体就是使用的iframe,大家可以尝试通过F12开发者模式查看到的tag_name,class_name,id或者xpath来定位中的页面元素,会抛出NoSuchElementException异常。解决

  9. python ffmpeg 使用 pyav 转换 一组图像 到 视频 - 2

    2022/8/4更新支持加入水印水印必须包含透明图像,并且水印图像大小要等于原图像的大小pythonconvert_image_to_video.py-f30-mwatermark.pngim_dirout.mkv2022/6/21更新让命令行参数更加易用新的命令行使用方法pythonconvert_image_to_video.py-f30im_dirout.mkvFFMPEG命令行转换一组JPG图像到视频时,是将这组图像视为MJPG流。我需要转换一组PNG图像到视频,FFMPEG就不认了。pyav内置了ffmpeg库,不需要系统带有ffmpeg工具因此我使用ffmpeg的python包装p

  10. Python 刷Leetcode题库,顺带学英语单词(31) - 2

    ValidPalindromeGivenastring,determineifitisapalindrome,consideringonlyalphanumericcharactersandignoringcases. [#125]Example:"Aman,aplan,acanal:Panama"isapalindrome."raceacar"isnotapalindrome.Haveyouconsiderthatthestringmightbeempty?Thisisagoodquestiontoaskduringaninterview.Forthepurposeofthisproblem

随机推荐