chinapnr / py-summer

Simplify and strengthen the Python web server development, mainly RESTful server, use Flask as the backend.
GNU General Public License v3.0
3 stars 1 forks source link

修改 test 或者 dev 环境的设置方式 #2

Open wingfish opened 6 years ago

wingfish commented 6 years ago

在jman 中实现是通过配置文件中设定 testing,development 等的,根据最佳实践的原则,修改为环境变量方式。

也就是不再用下面这类方式 ··· server_status = jarvis_man.dt['server']['status'] ···

而是用 export FLASK_ENV=development 这样来定义

并在配置文件中类似下面方式读入。

··· ENVIRONMENT_DEBUG = os.environ.get("DEBUG", default=False) if ENVIRONMENT_DEBUG.lower() in ("f", "false"): ENVIRONMENT_DEBUG = False ···

wingfish commented 6 years ago

__init__.py 中增加下面读取 conf 的函数 read_conf(),

from sum_server.config import DevelopmentConfig, TestingConfig

# 2018.7.4
def read_conf(app):

    server_env = os.environ.get('SERVER_ENV', default='development')

    # 根据 server 环境状态读入 flask config 对象
    if server_env == 'development':
        app.config.from_object(DevelopmentConfig)
        print(DevelopmentConfig.SQLALCHEMY_DATABASE_URI)
    elif server_env == 'testing':
        app.config.from_object(TestingConfig)

在 config.py 中代码如下:

from fishbase import fish_file as fff

class Config(object):
    DEBUG = False
    TESTING = False

# 生成 sqlite 数据库的 uri 字符串
def get_db_sqlite_uri(db_name):

    db_sqlite_uri = 'sqlite:///' + fff.get_abs_filename_with_sub_path('db', db_name)[1]

    return db_sqlite_uri

class DevelopmentConfig(Config):
    DEBUG = True
    SQLALCHEMY_DATABASE_URI = get_db_sqlite_uri('jdb_dev.sqlite')

class TestingConfig(Config):
    TESTING = True

具体配置都放在 config.py 的class 对象中,在 init 中根据不同的环境变量去读入;

比如 FLASK_ENV=development