python - pymongo - 如何通过 GridFS 中的索引创建/查询

标签 python pymongo gridfs

就我而言,我需要通过 SHA1 确保文件的唯一性(存储为文件名)

db = pymongo.MongoClient('localhost', 27017).test
gfs = gridfs.GridFS(db)

# How may I create a unique index in GridFS?
gfs.files.create_index([('filename', 1)], unique=True)

如果文件已经存储,则通过SHA1查找该文件。

sha1 = hashlib.sha1(file_content).hexdigest()
try:
    return gfs.put(file_content, filename=sha1)
except pymongo.errors.DuplicateKeyError:

    # How may I find files via criterion?
    return gfs.find( { 'filename': sha1 } )['_id']

有人能告诉我如何做这些事情吗?提前致谢。

最佳答案

您可以手动为具有自身哈希值的文件提供 _id 键,而不是创建索引。

import pymongo 
db = pymongo.MongoClient('localhost', 27017).test
gfs = gridfs.GridFS(db)

def hash(file):
   #some code to extract hash of a file from its content..

file_hash = hash(file)
if gfs.exists(_id=file_hash):
    #file exists!
else:
    #file does not exist in the database.
    gfs.put(file, _id=file_hash) #or do something else..

http://api.mongodb.org/python/current/api/gridfs/

关于python - pymongo - 如何通过 GridFS 中的索引创建/查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16051016/

相关文章:

Python BS4 表解析返回空列表

file - 我想要 GridFS 的好处,但主要存储 16MB 以下的文件

java - 如何使用spring mvc通过gridfs下载存储在mongodb中的文件

Python,将 mongodump 的 bson 输出转换为 json 对象数组(字典)

python - 在日期时间的月、日、年...上查询 Mongodb

python - 在批量更新中提供提示

java - MongoDb GridFs 更新 Java

python - uwsgi/nginx 上的 Flask 应用程序 - 启动时不创建 unix 套接字文件

python - 如何在 matplotlib 中连接/对齐轴以获得完美的角?

python - 当有多个规范时,在 Pandas 中优化计算的最佳做法是什么?