FastAPI 读取不同环境的配置文件

配置文件

config-dev.ini

# -*- coding: utf-8 -*-
# 数据库配置
[pgsql]
host=192.168.1.2
port=5432
dbname=test
user=root
passwd=xxxxxxxx

# Redis配置
[redis]
host=192.168.1.2
port=6379
password=xxxxxxxxx
db=0

读取配置

global_config.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
# @time    : 2023/2/3 14:00
# @author  : pugongying
# @description : 全局参数配置

import configparser
import os
import sys
from functools import lru_cache

# 设置 目录在项目跟目录下
cache_dir_name = 'cache'
base_path = os.path.dirname(__file__)
idx = base_path.index('app' + os.sep + 'config')
work_dir = base_path[:idx]

params = sys.argv


class ConfigSetting(object):

    def __init__(self, config_file='config-dev.ini'):
        self._path = os.path.join(work_dir + 'config', config_file)
        if not os.path.exists(self._path):
            raise FileNotFoundError("No such file: %s" % config_file)
        self._config = configparser.ConfigParser()
        self._config.read(self._path, encoding='utf-8')

    def get_work_dir(self):
        return work_dir

    def get_cache_dir(self):
        cache_dir_path = work_dir + cache_dir_name
        if not os.path.exists(cache_dir_path):
            # 目录不存在,创建目录
            os.mkdir(cache_dir_path)
        return cache_dir_path

    def get(self, section, name, strip_blank=True, strip_quote=True):
        s = self._config.get(section, name)
        if strip_blank:
            s = s.strip()
        if strip_quote:
            s = s.strip('"').strip("'")

        return s

    def getboolean(self, section, name):
        return self._config.getboolean(section, name)

    def getint(self, section, name):
        return self._config.getint(section, name)


class GlobalConfig(object):
    CONFIG_SETTING = ConfigSetting('config-%s.ini' % (
        params[1] if len(params) > 1 and params[1] in ['dev', 'test', 'pre', 'prod', 'local'] else 'dev'))

    # 工作目录
    WORK_DIR = CONFIG_SETTING.get_work_dir()
    # 缓存目录
    CACHE_DIR = CONFIG_SETTING.get_cache_dir()

    # PgSQL配置
    PgSQL_HOST = CONFIG_SETTING.get('pgsql', 'host')
    PgSQL_PORT = CONFIG_SETTING.get('pgsql', 'port')
    PGSQL_DBNAME = CONFIG_SETTING.get('pgsql', 'dbname')
    PGSQL_USER = CONFIG_SETTING.get('pgsql', 'user')
    PGSQL_PASSWD = CONFIG_SETTING.get('pgsql', 'passwd').replace('@', '%40') # 处理密码中有“@”特殊字符

    # Redis配置
    REDIS_HOST = CONFIG_SETTING.get('redis', 'host')
    REDIS_PORT = CONFIG_SETTING.get('redis', 'port')
    REDIS_PASSWORD = CONFIG_SETTING.get('redis', 'password')
    REDIS_DB = CONFIG_SETTING.getint('redis', 'db')


@lru_cache()
def get_configs():
    return GlobalConfig()


configs = get_configs()

使用配置

database.py

from app.config import configs

# pgsql 数据库url
SQLALCHEMY_DATABASE_URL = "postgresql://{}:{}@{}:{}/{}".format(
    configs.PGSQL_USER,
    configs.PGSQL_PASSWD,
    configs.PgSQL_HOST,
    configs.PgSQL_PORT,
    configs.PGSQL_DBNAME
)  

print("SQLALCHEMY_DATABASE_URL=", SQLALCHEMY_DATABASE_URL)

# 数据库迁移配置
engine = create_engine(SQLALCHEMY_DATABASE_URL, pool_pre_ping=True, pool_size=50, pool_timeout=30, pool_recycle=1)
SessionLocal = sessionmaker(autocommit=False, autoflush=True, bind=engine)
session = scoped_session(SessionLocal)

Base = declarative_base()


def get_db():
    db = session
    try:
        yield db
    finally:
        db.remove()
posted @ 2023-03-08 18:01  蒲公英PGY  阅读(687)  评论(0编辑  收藏  举报