2017-03-02 47 views
1

我正在構建Web刮板並嘗試爲實體分配UUID。在MongoDB中分配UUID並檢查網頁掃描器的重複內容

因爲一個實體可以在不同的時間刮,我想最初的UUID存儲與從網頁

// example document 
{ 
"ent_eid_type": "ABC-123", 
"ent_uid_type": "123e4567-aaa-123e456" 
} 
下面

提取的ID一起的是,對於在找到的每一個id字段上運行的代碼被刮掉的物品

# if the current ent_eid_type is a key in mongo... 
if db_coll.find({ent_eid_type: ent_eid}).count() > 0: 

    # return the uid value 
    ent_uid = db_coll.find({ent_uid_type: ent_uid }) 
else: 
    # create a fresh uid 
    ent_uid = uuid.uuid4() 

    # store it with the current entity eid as key, and uid as value 
    db_coll.insert({ent_eid_type: ent_eid, ent_uid_type: ent_uid}) 

# update the current item with the stored uid for later use 
item[ent_uid_type] = ent_uid 

控制檯正在返回KeyError: <pymongo.cursor.Cursor object at 0x104d41710>。不知道如何解析光標ent_uid

任何提示/建議表示讚賞!

回答

1

Pymongo查找命令返回你需要遍歷或訪問來獲取對象

訪問第一個結果光標對象(你已經選中一個存在),並訪問ent_uid領域。

大概你會搜索EID類型,ent_eid不是ent_uid。沒有理由搜索你是否已經擁有它。

ent_uid = db_coll.find({ent_eid_type: ent_eid })[0]['ent_uid'] 

或不擔心光標,使用find_one命令來代替(http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one

ent_uid = db_coll.find_one({ent_eid_type: ent_eid })['ent_uid']