2013-04-17 48 views
1

在我的情况下,通过索引/查询我需要确保文件的通过SHA1的独特性(存储为filenamepymongo - 如何创建GridFS的

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'] 

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

回答

1

而不是创建索引,您可以手动提供文件的_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/

+0

如果这个代码在并发环境中运行?我需要数据库来确保唯一性。 – neuront