为什么我会收到“FileField”对象没有属性“put”?
遵循http://mongoengine.org/docs/v0.4/guide/gridfs。关于 mongoengine FileField 的 html 文档 我做了以下操作:
在我的模型中
files = ListField(FileField())
在我的测试代码中
# Create an entry
photo = FileField()
f = open('/home/foo/marmot.jpg', 'r')
photo.put(f, content_type='image/jpeg')
entry.files = [photo,]
尝试遵循文档,但是我收到错误:
Traceback (most recent call last):
File "/home/bar/tests.py", line 76, in test_MongoDGACLogook_creation
photo.put(f, content_type='image/jpeg')
AttributeError: 'FileField' object has no attribute 'put'
我是否遗漏了一些明显的东西?
谢谢
Following http://mongoengine.org/docs/v0.4/guide/gridfs.html documentation about mongoengine FileField I did the following:
In my model
files = ListField(FileField())
In my test code
# Create an entry
photo = FileField()
f = open('/home/foo/marmot.jpg', 'r')
photo.put(f, content_type='image/jpeg')
entry.files = [photo,]
Trying to follow the doc, however i get an error:
Traceback (most recent call last):
File "/home/bar/tests.py", line 76, in test_MongoDGACLogook_creation
photo.put(f, content_type='image/jpeg')
AttributeError: 'FileField' object has no attribute 'put'
Am I missing something obvious ?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
IMO 中这一点并不明显,但如果您查看 Mongoengine 代码,您会发现
put
方法是在GridFSProxy
类中定义的,可通过FileField
中的描述符(__get__
和__set__
方法)。查看文档中的代码和示例,似乎访问或使用
FileField
的唯一方法是通过描述符......所以,collection.file_field
。鉴于这一切,我认为不可能使用现在存在的 Mongoengine API 来获得文件字段列表。
This isn't obvious at all IMO, but if you look at the Mongoengine code you'll see that the
put
method is defined in theGridFSProxy
class, which is accessed via a descriptor inFileField
(the__get__
and__set__
methods).Looking at the code and the examples in the docs, it appears the only way to access or use a
FileField
is through the descriptor....so,collection.file_field
.Given all this, I don't think it's possible to have a list of file fields using the Mongoengine API as it exists now.
如果您要上传多个文件并尝试将其保存为 ListField(FileField())
If you are uploading multiples files and trying to save it a ListField(FileField())
我有完全相同的问题。正如 GitHub 上的 @KoppeKTop 在这篇文章中所建议的,我终于使用这样的 EmbeddedDocument 扩展了我的模型(
Pet
):然后我可以使用添加新图像
这可能并不总是最好的选择,但我个人更喜欢它,因为我可以像往常一样使用模型,而无需必须与代理一起工作。如果需要的话,我还可以在将来保存其他照片元数据。
I had exactly the same problem. As suggested by @KoppeKTop on GitHub in this post, I finally extended my model (
Pet
) using an EmbeddedDocument like this:I can then add a new image using
This may not always be the best option, but personally I prefer it because I can work with models as usual without having to work with proxies. And I can also save other photo metadata in the future, if I need to.