gpt4 book ai didi

django - 如何在内存中创建文件(不是上传的文件)并通过 Django default_storage 保存到 FileField?

转载 作者:行者123 更新时间:2023-12-03 23:54:21 28 4
gpt4 key购买 nike

如果我要在内存中创建一个类似文件的 csv 对象,如下所示:

output_stream = io.StringIO()
sheet = pyexcel.get_sheet(records=data)
sheet.save_to_memory(file_type='csv', stream=output_stream)

我该怎么做才能使用 Django 将 output_stream 中的对象等文件保存到我的 default_storage 后端的文件中?
class Example(models.Model):
model_file = models.FileField(upload_to='', max_length=255, blank=True, null=True)

我试过这样的事情:
self.model_file.save(filename, ContentFile(output_stream.read()))

但我收到以下错误:
"TypeError: ('data must be bytes, received', <class 'str'>)"

pyexcel 仅支持 io.StringIO 流用于 csv 类型文件。

追溯:
...
File "C:\Users\Cole\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\files\storage.py", line 49, in save
return self._save(name, content)
File "C:\Users\Cole\AppData\Local\Programs\Python\Python36-32\lib\site-packages\storages\backends\gcloud.py", line 167, in _save
content_type=file.mime_type)
File "C:\Users\Cole\AppData\Local\Programs\Python\Python36-32\lib\site-packages\google\cloud\storage\blob.py", line 1034, in upload_from_file
size, num_retries, predefined_acl)
File "C:\Users\Cole\AppData\Local\Programs\Python\Python36-32\lib\site-packages\google\cloud\storage\blob.py", line 947, in _do_upload
size, num_retries, predefined_acl)
File "C:\Users\Cole\AppData\Local\Programs\Python\Python36-32\lib\site-packages\google\cloud\storage\blob.py", line 759, in _do_multipart_upload
transport, data, object_metadata, content_type)
File "C:\Users\Cole\AppData\Local\Programs\Python\Python36-32\lib\site-packages\google\resumable_media\requests\upload.py", line 94, in transmit
data, metadata, content_type)
File "C:\Users\Cole\AppData\Local\Programs\Python\Python36-32\lib\site-packages\google\resumable_media\_upload.py", line 270, in _prepare_request
raise TypeError(u'`data` must be bytes, received', type(data))
TypeError: ('`data` must be bytes, received', <class 'str'>)

最佳答案

您可以从 StringIO 阅读内容。并像这样转换为 utf8 编码的字节。

self.model_file.save(filename, ContentFile(output_stream.getvalue().encode()))
getvalue()类似于 read() ,但无论当前流位置如何,您都将始终获得 StringIO 的完整内容。与 read()您可能需要使用 seek(0) 倒带.

关于django - 如何在内存中创建文件(不是上传的文件)并通过 Django default_storage 保存到 FileField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51460152/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com