如何根据烧瓶中的测试和生产环境分配设置?

时间:2016-02-02 06:25:25

标签: python flask

我想根据各种条件(如测试和生产)分配不同的设置。因此,我希望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

1 个答案:

答案 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