0

I am creating a web application to manage invoice data using MongoDB, pymongo, and Bottle. Currently in a class created to handle the insertion to and reading from the database I have written a function to read each element of a given document and another one to insert new documents based on input given from an html form.

#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

However, the html page can accept more than just one item, quantity, and color, in order to account for orders with multiple items. I wanted to know what the best practice was to update my functions to include a variable number of parameters without knowing ahead of time how many the user will input. Each additional item would be labelled item# with the "#" replaced with the number item inserted of the order, so for example item5 for the 6th item inserted (starting from 0). The same goes for the quantity and color fields of the input. My initial thought was to insert a list of the items into the document rather than insert each item separately, but I was not sure the best way to go about this.

sreisman
  • 658
  • 3
  • 9
  • 24
  • Have you looked into `**kwargs`? http://stackoverflow.com/questions/1769403/understanding-kwargs-in-python – woozyking Jul 22 '13 at 19:15
  • Are you asking a question about Python, about Bottle, or about Mongo/pymongo? From your wording, my guess is that you're asking, "How do I insert a list into MongoDB?" Am I catching your drift? – ron rothman Jul 22 '13 at 21:05

1 Answers1

1

Just take a list (of dicts):

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

Call insert_names with a list that you generate from your html form.

names = [
    {'name': name0, 'qty': qty0, ...}
    {'name': name1, 'qty': qty1, ...}
    {'name': name2, 'qty': qty2, ...}
    ...
]
insert_names(names)
ron rothman
  • 17,348
  • 7
  • 41
  • 43