我想根据各种条件(如测试和生产)分配不同的设置。因此,我希望create_app
接受指示设置的参数,并使create_app
加载不同的设置,如下所示。
app.py
def create_app(config_file):
app.config['setting'] = config_file['setting']
if __name__ == "__main__":
app = create_app(production_setting)
app.run(host='0.0.0.0', port=config.SERVER_PORT, threaded=True, debug=True)
views.py
import stuff
if app.config['setting'] == 'testing':
print app.config['setting']
test_views.py
@pytest.fixture
def client():
testing_setting['setting'] = 'stuff'
app = create_app(testing_setting)
client = app.test_client()
return client
但是当我运行python app.py时出现此错误:
AttributeError: 'module' object has no attribute 'config'
有没有办法将参数从app
传递到views
?
答案 0 :(得分:2)
以下是我的表现:
def create_app(config=None):
app = Flask(__name__)
if not config:
config = 'your_app.config.Production'
app.config.from_object(config)
config.py,与包含create_app
的文件对等:
class BaseConfig(object):
SOME_BASE_SETTINGS = 'foo'
DEBUG = False
class Development(BaseConfig):
DEBUG = True
class Production(BaseConfig):
pass
这允许您的应用默认为制作,但例如,您可以在创建用于开发的应用时传递不同的配置名称:
create_app('your_app.config.Development')
有关此内容和类似示例的详细信息,请查看documentation