【问题标题】:MongoDB data PostingMongoDB数据发布
【发布时间】:2013-07-23 05:22:05
【问题描述】:

我正在创建一个 Web 应用程序来使用 MongoDB、pymongo 和 Bottle 来管理发票数据。目前,在一个为处理数据库的插入和读取而创建的类中,我编写了一个函数来读取给定文档的每个元素,另一个函数根据来自 html 表单的输入插入新文档。

#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 页面可以接受不止一种商品、数量和颜色,以便说明包含多个商品的订单。我想知道在不提前知道用户将输入多少参数的情况下更新我的函数以包含可变数量的参数的最佳做法是什么。每个额外的项目都将被标记为 item#,其中“#”替换为订单中插入的编号项目,例如 item5 表示插入的第 6 个项目(从 0 开始)。输入的数量和颜色字段也是如此。我最初的想法是在文档中插入一个项目列表,而不是单独插入每个项目,但我不确定最好的方法。

【问题讨论】:

  • 你看过**kwargs吗? stackoverflow.com/questions/1769403/…
  • 您是在问有关 Python、Bottle 或 Mongo/pymongo 的问题吗?根据您的措辞,我猜您是在问,“如何将列表插入 MongoDB?”我明白你的意思了吗?

标签: python mongodb pymongo bottle


【解决方案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

使用您从 html 表单生成的列表调用 insert_names。

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

【讨论】:

    猜你喜欢
    • 2018-11-27
    • 2015-03-30
    • 2018-06-22
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 2018-01-07
    • 2020-08-13
    • 1970-01-01
    相关资源
    最近更新 更多