问题描述
我遵循了来自 http:/的 Flask 项目的布局/blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world.
我有以下结构:
app/
__init__.py
views.py
forms.py
myFile.py
run.py
config.py
在views.py、forms.py中我可以使用
In views.py, forms.py I am able to use
from config import basedir
但是我不能在 myFile.py 中使用它
However I cannot use that in myFile.py
我加了
import Flask
当我修改它时,Flask Web 服务器会重新启动,但它并没有说在 app/myFile.py 中找到了更改,重新启动它只是重新启动.
and when I modify it, the Flask web server restarts, but it doesn't say found changes in app/myFile.py restarting it just restarts.
我需要做什么才能使用
from config import basedir
在我的python文件中.我没有看到在 __init__.py
中为 forms.py 做了什么特别的事情.
in my python file. I don't see anything special being done in __init__.py
for forms.py.
这是我的 __init__.py
文件:
from flask import Flask
from config import basedir
app = Flask(__name__)
app.config.from_object('config')
from app import views
推荐答案
当人们谈论 Flask 中的配置时,他们通常是在谈论将值加载到应用程序的配置中.在上面的示例中,您的 init.py
文件中可能有类似 app.config.from_object('config')
的内容.然后所有的配置值将被加载到 app.config
字典中.
When people talk about configs in Flask, they are generally talking about loading values into the app's configuration. In your above example you could have something like app.config.from_object('config')
in your init.py
file. Then all the configuration values will be loaded into the app.config
dictionary.
然后在您的任何文件中,您只需导入 app 对象即可访问该字典.我倾向于通过执行 from flask import current_app as app
然后只是 app.config['MY_SETTING']
来获取值来访问该 app
对象我很在乎.在文档中阅读更多内容.
Then in any of your files you could just import the app object to gain access to that dictionary. I tend to access that app
object by doing from flask import current_app as app
then just app.config['MY_SETTING']
to get the value I care about. Read up more in the documenation.
这篇关于如何从 Flask 中的配置文件导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!