【问题标题】:Mongodb seems to load data twice. Not sure why and not sure if I'm loading mongodb rightMongodb 似乎加载了两次数据。不知道为什么,也不确定我是否正确加载了 mongodb
【发布时间】:2020-08-07 23:07:56
【问题描述】:

我正在尝试让我的烧瓶应用程序将 csv 文件加载到 mongodb 中,然后将数据显示回来。出于某种原因,在我的应用程序的某个地方,数据被重复了。真的不知道如何调试它,也不确定我是否首先在正确的位置设置数据加载。任何意见,将不胜感激。相关代码如下:

from flask import Flask, render_template, request, redirect
import pymongo
from pymongo import MongoClient

import io
import csv
import json
import ast

app = Flask(__name__)
client = MongoClient("mongodb://db:27017")
db = client.projectDB
""" 
HELPER FUNCTIONS
"""

def loadDB():
    print("Initializing mongodb client")
    
    db_collection = db['recipe_data']
    #Uniqueness constraint for name, not necessary?
    # db_collection.createIndex( { "name": 1 }, { unique: true } )
    if db_collection.count() == 0:
        recipes = db_collection.recipes
        loaded_recipes_list = loadRecipes()
        for recipe in loaded_recipes_list:
            recipes.insert_one(recipe)
    print("Database loaded successfully!")

def loadRecipes():
    recipe_data = []

    #Load recipes
    csv_file = "./recipes_short.csv"
    rows = io.open(csv_file, "r", encoding="utf-8")
    reader = csv.reader(rows)
    for data in reader:
        recipe = {}
        recipe['name'] = data[0]
        recipe['id'] = data[1]
        recipe['minutes'] = data[2]
        recipe['contributor_id'] = data[3]
        recipe['submitted'] = data[4]
        recipe['tags'] = data[5].lstrip('[').rstrip(']').replace("'", "").split(',')
        recipe['n_steps'] = data[6].lstrip('[').rstrip(']').replace("'", "").split(',')
        recipe['steps'] = data[7]
        recipe['description'] = data[8].lstrip('[').rstrip(']').replace("'", "").split(',')
        recipe['ingredients'] = data[9]
        recipe['n_ingredients'] = data[10].lstrip('[').rstrip(']').replace("'", "").split(',')
        recipe_data.append(recipe)
    print(recipe_data)
    return recipe_data

@app.route("/")
def home():
    return render_template('index.html')


if __name__ == '__main__':
    loadDB()
    app.run(debug=True,host='0.0.0.0')

【问题讨论】:

  • 要补充一点,我正在使用 docker 部署应用程序,flask 文件夹是一个共享挂载。我注意到,每当我更改并保存烧瓶代码时,它都会创建更多重复项。我猜这是正常的,但它可能是一个线索。

标签: python mongodb flask duplicates load


【解决方案1】:

这是因为您使用 debug=True 运行烧瓶。这将在启动时重新加载文件,因此将运行您的数据加载器两次。

如果您取消标记(无论如何您都应该在生产中这样做),它将不会重新加载。

【讨论】:

  • 感谢您的回答。如果我在创建后立即在 docker 映像中加载 mongodb 数据,您认为这会解决吗?
  • 如果您担心重复数据,使用 recipe_id 和 upsert=True 上的过滤器将插入更改为 update_one() 可能会更容易
猜你喜欢
  • 2012-09-03
  • 2022-12-24
  • 1970-01-01
  • 2016-12-16
  • 2020-04-06
  • 2019-02-15
  • 2012-05-27
  • 1970-01-01
  • 2012-07-31
相关资源
最近更新 更多