如何从Flask中的配置文件导入

如何从Flask中的配置文件导入

本文介绍了如何从Flask中的配置文件导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 http://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.

然后在任何文件中,您只需导入应用程序对象即可访问该字典.我倾向于通过执行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中的配置文件导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 08:44