我正在嘗試讓我的燒瓶應用程序將 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 [email protected]("/")def home(): return render_template('index.html')if __name__ == '__main__': loadDB() app.run(debug=True,host='0.0.0.0')
Mongodb 似乎加載了兩次數據。不知道為什么,也不確定我是否正確加載了 mongodb
慕碼人8056858
2023-05-09 10:13:51