python 环境变量区分

python 环境变量区分

设置并获取环境变量

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"]
推荐第一种,提供默认值不会报错

通过配置模块configparser读取配置

安装

pip install configparser
  1. config类
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')
  1. 配置文件
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 环境变量配置

scrapy 支持环境变量区分环境,有两种配置方式:1. SCRAPY_SETTINGS_MODULE(默认settings), 2.SCRAPY_PROJECT

scrapy 环境区分: scrapy 会读取环境变量 SCRAPY_PROJECT ,若没有缺省值default

  1. 新建settings.py文件,test_settings.py;
  2. scrapy.cfg [settings] 中添加新增的settings.py文件名,test=[projectname].test_settings
 [settings]                                                                               
 default = projectname.settings                                                                
 test = projectname.settings 
 
 prod = projectname.settings 
  1. export SCRAPY_PROJECT=test;
  2. scrapy crawl spidername

代码中直接使用 settings

from scrapy.utils.project import get_project_settings

# 字典用法
settings = get_project_settings()

通过钩子获取 settings

@classmethod
def from_settings(cls, settings):
    # 获取settings
    settings['test']

你可能感兴趣的:(Python,python)