我正在尝试让我的烧瓶应用程序将 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')
尚方宝剑之说
相关分类