【问题标题】:Weird behavior in request.FILES and File and handler in DjangoDjango 中 request.FILES 和 File 和处理程序中的奇怪行为
【发布时间】:2014-10-20 05:52:45
【问题描述】:

我有一个同时上传两个文件的请求。 request 对象的 FILES 属性如下所示:

<MultiValueDict: {u'output': [<InMemoryUploadedFile: output.txt (text/plain)>], u'history': [<InMemoryUploadedFile: .history.json (application/octet-stream)>]}>

我将两个文件都存储为变量:

output = request.FILES['output']
history = request.FILES['history']

然后我将 Django 模型上的两个文件字段分配给这些文件以尝试保存它们,但只有分配给 output 的文件字段被正确保存,另一个应该包含历史内容的字段包含没有内容。

尝试在调试器中解决此问题后,我发现我只能读取一次history 的内容,之后history.read() 返回一个空字符串:''output 可以读取任意多次,它仍然返回 outputs 的实际内容。

我尝试了许多不同的 hacky 策略来保存 history 的内容,包括使用 FileContentFile 创建新文件,但似乎 django 正在无视我创建返回文件的任何尝试这个内容在.read()

作为记录,history 包含大量采用有效 JSON 格式且大小约为 12k 的二进制数据。 file 说是:

ASCII text, with very long lines, with no line terminators

Django 处理history 的方式有什么遗漏吗?

编辑:以下是我要保存的模型上的字段(尽管我相信问题在保存之前发生):

   history_file = models.FileField(
        upload_to=history_file_name,
        null=True,
        blank=True
    )
    output_file = models.FileField(
        upload_to=output_file_name,
        null=True,
        blank=True
    )

这是保存模型的代码:

    result.output_file = output
    challenge.history_file = history
    challenge.save()

此问题出现在基于 View 的 CBV 的 post 方法中。 我没有更改 Django 1.6.5 附带的任何默认文件处理设置

【问题讨论】:

  • 能否将保存文件内容的代码包含在模型中?
  • 您可以在设置值和保存模型的位置添加代码吗?
  • 也完成了!很抱歉之前没有添加它

标签: python django http django-views django-file-upload


【解决方案1】:

我仍然不确定为什么会这样,但我可以通过执行以下操作来解决这个问题:

history = files['history']
history_content = history.read()
from django.core.files.base import ContentFile
history_content_file = ContentFile(history_content)
challenge.history_file.save(NAME, history_content_file)

郑重声明,history_content_file 只能读取一次。

希望这可以帮助其他人,如果我明白这里发生了什么,我会发布更多信息。

【讨论】:

    猜你喜欢
    • 2013-04-29
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    相关资源
    最近更新 更多