当将PyMongo驱动程序用于MongoDB时,我能够使用bucket.upload_from_stream(文件名,地址)将图像成功上传到GridFS。它非常简单,没有任何复杂性。但是,当我尝试使用第二个参数作为目标并使用bucket.download_to_stream_by_name(filename, address)
检索相同的数据时,会引发错误:
AttributeError: 'unicode' object has no attribute 'write'
为什么会这样?如何设置文件保存位置?
这是使用download_to_stream_by_name并在磁盘上的目录中创建文件的示例:
import os
from pymongo import MongoClient
from gridfs import GridFSBucket
my_db = MongoClient().test
fs = GridFSBucket(my_db)
file_id = fs.upload_from_stream(
"test_file",
"data I want to store!",
chunk_size_bytes=4,
metadata={"contentType": "text/plain"})
fs = GridFSBucket(my_db)
# Get file to write to
if not os.path.exists('my_directory'):
os.makedirs('my_directory')
file = open('my_directory/myfile','wb')
fs.download_to_stream_by_name("test_file", file)
“类似文件的对象”是具有“写入”方法的方法,该方法需要大块字符来写入。通过“打开”功能创建的实际文件对象是类似文件的对象的一种可能性。
注意,传递给download_to_stream_by_name的文件名是GridFS中的文件名,而不是磁盘上的文件名。