Flask 配置使用问题。访问配置项时出现KeyError
Issues with flask config usage. Having a KeyError when accessing a configuration item
我已经确保我阅读了所有可能的 post 内容,但似乎有些内容对我来说仍然很模糊。我正在通过使用 Flask 做一个项目来学习 python。我的文件夹结构如下图
/source
/config
__init__.py
settings.py
/classes
__init__.py
Dblayer.py
/templates
index.html
test.html
myapp.py
所以在我的应用程序中我使用了以下内容
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'])
settings.py的内容真的很简单:
database = "somedb"
username = "someuser"
password = "somepassword"
host = "localhost"
我用 test.html 查看了 flask 中配置的使用情况,我遇到了一个非常烦人的 KeyError:'host'。我有什么做的不好吗?
谢谢
来自the docs:
Only values in uppercase are actually stored in the config object
later on. So make sure to use uppercase letters for your config keys.
很容易错过。
仅使用大写重命名您的配置变量。
另一件需要注意的事情是,您不必将配置变量或该字典中的任何特定值传递给 jinja2 模板引擎。 Flask 暴露了它们。基本上,去掉 db= app.config['host']
、config['host'],所有其他配置变量在所有模板中都已经可用。有关详细信息,请参阅 here。
我已经确保我阅读了所有可能的 post 内容,但似乎有些内容对我来说仍然很模糊。我正在通过使用 Flask 做一个项目来学习 python。我的文件夹结构如下图
/source
/config
__init__.py
settings.py
/classes
__init__.py
Dblayer.py
/templates
index.html
test.html
myapp.py
所以在我的应用程序中我使用了以下内容
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'])
settings.py的内容真的很简单:
database = "somedb"
username = "someuser"
password = "somepassword"
host = "localhost"
我用 test.html 查看了 flask 中配置的使用情况,我遇到了一个非常烦人的 KeyError:'host'。我有什么做的不好吗?
谢谢
来自the docs:
Only values in uppercase are actually stored in the config object later on. So make sure to use uppercase letters for your config keys.
很容易错过。
仅使用大写重命名您的配置变量。
另一件需要注意的事情是,您不必将配置变量或该字典中的任何特定值传递给 jinja2 模板引擎。 Flask 暴露了它们。基本上,去掉 db= app.config['host']
、config['host'],所有其他配置变量在所有模板中都已经可用。有关详细信息,请参阅 here。