flask配置使用问题。访问配置项时出现KeyError

bla*_*sei 2 python flask

我确保已阅读所有有关此内容的可能文章,但似乎对我来说仍然有些模糊。我正在通过烧瓶进行项目学习python。我的文件夹结构如下图所示

/source
  /config
  __init__.py
  settings.py
  /classes
  __init__.py
  Dblayer.py
  /templates
  index.html
  test.html
myapp.py
Run Code Online (Sandbox Code Playgroud)

因此,在我的应用中,我正在使用以下内容

from flask import Flask, request, session, g, redirect, url_for, abort, render_template
from classes import DbLayer

app = Flask(__name__)
app.config.from_pyfile("config/settings.py") # this is according to documentation...so I am confused


@app.route('/')
def index():
    return render_template("index.html")


@app.route('/viewitems')
def showitems():
    return render_template("test.html", db= app.config['host'])  
Run Code Online (Sandbox Code Playgroud)

settings.py的内容非常简单:

database = "somedb"
username = "someuser"
password = "somepassword"
host = "localhost"
Run Code Online (Sandbox Code Playgroud)

我使用test.html查看flask中的配置用法,并且遇到了非常烦人的KeyError:“主机”。我有什么不好的地方吗?

谢谢

GG_*_*hon 6

文档

稍后仅将大写值实际存储在config对象中。因此,请确保对配置密钥使用大写字母。

很容易错过。

仅使用大写字母重命名配置变量。

需要注意的另一件事是,您不必将config变量或该字典中的任何特定值传递给jinja2模板引擎。烧瓶将它们暴露。基本上,删除db= app.config['host'],config ['host']和所有其他配置变量已在所有模板中可用。有关更多详细信息,请参见此处