2013-04-17 3 views
1

에서 인덱스로/쿼리를 만드는 방법 I합니다 (filename로 저장) SHA1를 통해 파일의 고유성pymongo - 내 경우 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