import os
from flask import Flask, render_template, redirect, request, url_for
from pymongo import MongoClient
from bson.objectid import ObjectId
#connect to mongodb
app = Flask(__name__)
client = os.environ.get('MONGO_URI')
db = client.recipebook
@app.route('/')
#returning the index.html template
def index():
recipes = [recipe for recipe in db.recipes.find({})]
return render_template('index.html', recipes=recipes)
#setting up flask
if __name__ == '__main__':
app.run(host=os.getenv('IP'), port=os.getenv('PORT'), debug=True)
我期望的结果是我的连接字符串能够成功工作。当我的代码中确实有完整的URI时,它确实可以工作。但是当我使用环境变量时,我得到了错误消息:
”第9行,在 db:MongoClientobject = client.recipebook AttributeError:“ str”对象没有属性“ recipebook””
当我一起删除第9行时,我获得了一个成功的连接,但错误消息为“ NameError:未定义名称'db'”