2013-07-22 54 views
0

我正在創建一個web應用程序來使用MongoDB,pymongo和Bottle來管理髮票數據。目前在爲處理插入和讀取數據庫而創建的類中,我編寫了一個函數來讀取給定文檔的每個元素,另一個函數根據從html表單輸入的內容插入新文檔。MongoDB數據發佈

#This function will handle the finding of orders 
    def find_names(self): 
     l = [] 
     for each_name in self.myorders.find(): 
      l.append({'_id':each_name['_id'], 'quote':each_name['quote'],'name': each_name['name'], 'item': each_name['item'], 'qty': each_name['qty'], 'color': each_name['color'], 'phone': each_name['phone'], 'email':each_name['email']}) 
     return l 

#This function will handle the insertion of orders 
    def insert_name(self, newname, newitem, newqty, newcolor, newphone, newemail, newquote): 
     creationTime = datetime.datetime.now() 
     newname = {'name':newname, 'created' :creationTime, 'item' :newitem, 'qty':newqty, 'color':newcolor, 'phone':newphone, 'email' :newemail, 'quote' :newquote} 
     _id = self.myorders.insert(newname) 
     return _id 

但是,html頁面可以接受多個項目,數量和顏色,以便爲具有多個項目的訂單進行報賬。我想知道什麼是最佳做法是更新我的功能,以包含可變數量的參數,而不提前知道用戶將輸入多少。每個附加項目將被標記爲項目#,其中「#」被替換爲插入訂單的編號項目,因此例如插入第6項目的item5(從0開始)。輸入的數量和顏色字段也是如此。我最初的想法是將這些項目列表插入到文檔中,而不是分別插入每個項目,但我不確定最好的解決方法。

+0

你看過「** kwargs」嗎? http://stackoverflow.com/questions/1769403/understanding-kwargs-in-python – woozyking

+0

您是否在問關於Python,關於Bottle或關於Mongo/pymongo的問題?從你的措辭來看,我的猜測是你問,「我如何在MongoDB中插入一個列表?」我抓住你的漂移嗎? –

回答

1

只取(的類型的字典)的列表:

def insert_names(self, names): 
    # `names` is a list of dicts 

    inserted_ids = [] 

    for name in names: 
     name['created'] = datetime.datetime.now() 
     _id = self.myorders.insert(name) 
     inserted_ids.append(_id) 

    return inserted_ids 

呼叫insert_names與你從你的HTML表單生成一個列表。

names = [ 
    {'name': name0, 'qty': qty0, ...} 
    {'name': name1, 'qty': qty1, ...} 
    {'name': name2, 'qty': qty2, ...} 
    ... 
] 
insert_names(names)