python - 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'未定义”
解决方案
推荐阅读
- spring - WebClient 在请求写入完成之前不会读取响应。
- c# - 硒可访问性测试
- c# - 非托管导出 System.MissingMethodException
- python - pygame中未显示文本
- css - CSS 文件未在 Laravel 视图中加载
- google-compute-engine - 如何使用 terraform 将多个外部 IP 分配给谷歌云实例
- elasticsearch - 将创建索引请求的映射与服务器的映射进行比较
- jsreport - 带有 Chrome-pdf 配方的 JsReport 页码
- php - 如何动态分配作者在 WordPress 中发帖?
- node.js - 无需 console.log 即可获取数据