os.getenv os.environ
设置环境变量
1. 启动时设置
PROFILE=test python3 main.py
2. linux export 导入环境变量
export PROFILE=test
获取环境变量
1. os.getenv("PROFILE", "test")
2. os.environ["PROFILE"]
推荐第一种,提供默认值不会报错
安装
pip install configparser
class Config(object):
PROFILE = "dev"
MYSQL_URL = 'XXX'
class ProdConfig(Config):
'''
生产环境配置
'''
PROFILE = "prod"
MYSQL_URL = 'XXX'
class TestingConfig(Config):
'''
测试环境配置
'''
PROFILE = "test"
MYSQL_URL = 'XXX'
配置类获取配置
import configparser
if env == 'dev':
app.config = config.DevelopmentConfig
elif env == 'test':
app.config = config.TestingConfig
elif env == 'prod':
app.config = config.ProdConfig
else:
raise ValueError('Invalid environment')
test_conf.json
prod_conf.json
配置文件获取配置类
import os
import configparser
try:
CONFIG_PATH = os.environ['CONFIG_PATH']
except Exception:
raise ValueError
config = configparser.ConfigParser()
config.read(CONFIG_PATH)
scrapy 支持环境变量区分环境,有两种配置方式:1. SCRAPY_SETTINGS_MODULE(默认settings), 2.SCRAPY_PROJECT
scrapy 环境区分: scrapy 会读取环境变量 SCRAPY_PROJECT ,若没有缺省值default
[settings]
default = projectname.settings
test = projectname.settings
prod = projectname.settings
代码中直接使用 settings
from scrapy.utils.project import get_project_settings
# 字典用法
settings = get_project_settings()
通过钩子获取 settings
@classmethod
def from_settings(cls, settings):
# 获取settings
settings['test']