Flask配置文件无效

时间:2016-02-11 06:44:47

标签: python flask configuration-files

flask documentation,我试图在我的项目中实现配置。但它似乎没有按预期工作。我可能错了。但我不明白我错过了什么。

class Config(object):
    DEBUG = False
    TESTING = False
    CSRF_ENABLED = True
    TIMEOUT_COUNT=60
    DBCONFIG ={
      'DBNAME' : 'dbname',
      'DBUSER' : 'laxmikant',
      'DBPASSWORD' : '*******',
      'DBHOST' : 'localhost'
    }

class ProductionConfig(Config):
    SERVER_NAME = 'PRODUCTION'
    dbcredentials = {'DBUSER' : 'produser', 'DBPASSWORD':'******'}
    Config.DBCONFIG.update(dbcredentials)

class DevelopmentConfig(Config):
    SERVER_NAME = 'DEVELOPMENT'
    DEVELOPMENT = True
    TESTING = True
    DEBUG = True
    dbcredentials = {'DBUSER' : 'devuser', 'DBPASSWORD':'******'}
    Config.DBCONFIG.update(dbcredentials)

在运行python run.py之前,我按照环境设置APP_SETTINGS

export APP_SETTINGS="config.ProductionConfig" #- on production server
export APP_SETTINGS="config.DevelopmentConfig" #- on dev server

我读了配置文件并为服务器打印了DBCONFIG:

   environment = os.environ['APP_SETTINGS']
   app.config.from_object(environment)
   print '''[{}]  INFO {}'''.format(app.config['SERVER_NAME'], app.config['DBCONFIG'])

以下是生产服务器的实际输出:

$ export APP_SETTINGS="config.ProductionConfig"
laxmikant:~/workspace/project-xyz$ python run.py 
[PRODUCTION]  INFO {'DBPASSWORD': '******', 'DBUSER': 'devuser', 'DBHOST': 'localhost', 'DBNAME': 'dbname'}
[02-10 2016 22:39:33]  INFO - * Running on http://0.0.0.0:3004/ (Press CTRL+C to quit)

对于DEV Server

$ export APP_SETTINGS="config.DevelopmentConfig"
laxmikant:~/workspace/project-xyz$ python run.py 
[DEVELOPMENT]  INFO {'DBPASSWORD': '******', 'DBUSER': 'devuser', 'DBHOST': 'localhost', 'DBNAME': 'dbname'}
[02-10 2016 22:41:40]  INFO - * Running on http://0.0.0.0:3004/ (Press CTRL+C to quit)

查询是,为什么development和制作config提供相同的DBCONFIG信息?

**注意** - 我不会使用python run.py进行制作,但在这里我只需要测试配置。所以请忽略python run.py

1 个答案:

答案 0 :(得分:1)

您正尝试在子类中更新相同的父类字典。尝试复制并更新它:

class ProductionConfig(Config):
    dbcredentials = {'DBUSER' : 'produser', 'DBPASSWORD':'******'}
    DBCONFIG = Config.DBCONFIG.copy()
    DBCONFIG.update(dbcredentials)

class DevelopmentConfig(Config):
    dbcredentials = {'DBUSER' : 'devuser', 'DBPASSWORD':'******'}
    DBCONFIG = Config.DBCONFIG.copy()
    DBCONFIG.update(dbcredentials)