我正在尝试让我的烧瓶应用程序将 csv 文件加载到 mongodb 中,然后显示回数据。出于某种原因,在我的应用程序中的某个地方,应用程序的数据被复制了。真的不知道如何调试它,也不确定我是否首先在正确的位置设置了数据加载。任何意见,将不胜感激。相关代码如下:from flask import Flask, render_template, request, redirectimport pymongofrom pymongo import MongoClientimport ioimport csvimport jsonimport astapp = 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')
1 回答
尚方宝剑之说
TA贡献1788条经验 获得超4个赞
这是因为你正在运行烧瓶debug=True
。这将在启动时重新加载文件,因此将运行您的数据加载程序两次。
如果您取下标志(无论如何您都应该在生产中这样做),它不会重新加载。
添加回答
举报
0/150
提交
取消