首页 > 解决方案 > AttributeError:“str”对象没有属性“recipebook”

问题描述

我试图为我的 db URI 创建一个环境变量。当我在不使用 ev 的情况下对 URI 进行硬编码时,它可以正常工作。当我尝试使用 ev 我不成功。

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'未定义”

标签: pythondatabase

解决方案


推荐阅读