【问题标题】:How to structure form data within MongoDB (Python/Flask)如何在 MongoDB (Python/Flask) 中构造表单数据
【发布时间】:2018-12-12 12:11:51
【问题描述】:

我在 MongoDB 中从用户表单构建数据时遇到问题。

我理想的文档结构是这样的:

如您所见,成分位于可迭代的数组中。

但是,在提交表单时,我无法找到方法来执行此操作。我的成分部分的表格如下所示:

 <h4>Ingredients</h4>
        </div>
        <div class="row">
            <div class="input-field col s6">
                <input id="ingredients_1_name" name="ingredients_name_1" type="text" class="validate" required>
                <label for="ingredients_1_name">Ingredient</label>
            </div>
            <div class="input-field col s3">
                <input id="ingredients_1_quantity" name="ingredients_quantity_1" type="text" class="validate" required>
                <label for="ingredients_1_quantity">Quantity</label>
            </div>
            <div class="input-field col s3">
                <input id="ingredients_1_unit" name="ingredients_unit_1" type="text" class="validate" required>
                <label for="ingredients_1_unit">Unit</label>
            </div>
        </div>

用户可以按下一个 JavaScript 按钮,添加一个名为“ingredients_2_name”的新行,依此类推。这导致了一个非常非结构化的数据库:

这显然是一团糟,在使用数据时需要进行不必要的操作。

我似乎在网上找不到任何关于如何以定义的方式将数据从 HTML 表单发送到 MongoDB 的信息。

目前在提交表单时,视图如下:

@app.route('/insert_recipe/', methods=['GET','POST'])
def insert_recipe():
    """
    This function is called when a user clicks the submit button on the add
    recipe form. Uses the insert_one() method to add to the recipes document.
    """
    recipes = mongo.db.recipes
    dictionary = recipes.insert_one(request.form.to_dict())
    return redirect(url_for("get_recipes"))

这只是将输入名称作为键,将用户输入作为值。

是否有人能够描述我如何以结构化的方式在 MongoDB 中存储表单数据?

【问题讨论】:

    标签: python html mongodb flask pymongo


    【解决方案1】:

    您需要将纯 HTML-form-post 请求转换为类似 JSON 的结构,而无需任何数据操作。我非常怀疑这是否可行,因为 JSON 对象使用 嵌套 数据和键/索引方法来访问它,而 HTML-form-post 数据是 flat 并且遵循唯一性-id-approach 来访问它的数据。我可以看到 2 种可能的解决方案:

    1. 使用序列化库 WTForms,它将为您执行 python-data -> html-form -> python-data 转换,您不必自己进行不必要的操作
    2. 以 JSON 对象的形式为您创建一个网页(前端)发布请求。

    【讨论】:

      猜你喜欢
      • 2017-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-23
      • 2017-07-22
      • 2019-04-27
      • 1970-01-01
      相关资源
      最近更新 更多