62 lines
1.8 KiB
Python
62 lines
1.8 KiB
Python
import os
|
|
from configparser import ConfigParser
|
|
from typing import Optional
|
|
from pydantic import BaseSettings
|
|
from fastapi_plugins import RedisSettings
|
|
|
|
|
|
class ReConfigParser(ConfigParser):
|
|
def __init__(self, defaults=None):
|
|
ConfigParser.__init__(self, defaults=defaults)
|
|
|
|
"""复写方法实现key值区分大小写"""
|
|
def optionxform(self, optionstr):
|
|
return optionstr
|
|
|
|
# class CommonConfig(BaseSettings):
|
|
# SECRET_KEY: str = os.urandom(32)
|
|
# PROJECT_NAME: str
|
|
# API_V1_STR: str
|
|
# # 允许访问的origins
|
|
# BACKEND_CORS_ORIGINS: str
|
|
|
|
|
|
class MySQLConfig(BaseSettings):
|
|
username: str
|
|
password: str
|
|
host: Optional[str] = "localhost"
|
|
port: Optional[int] = 3306
|
|
database: str
|
|
|
|
@property
|
|
def sqlalchemy_db_uri(self):
|
|
return f"mysql+pymysql://{self.username}:{self.password}@{self.host}:{self.port}/{self.database}?charset=utf8"
|
|
|
|
|
|
class RedisConfig(RedisSettings):
|
|
redis_url: str = None
|
|
redis_host: Optional[str] = 'localhost'
|
|
redis_port: Optional[int] = 6379
|
|
redis_password: str = None
|
|
redis_db: int = 0
|
|
redis_connection_timeout: int = 2
|
|
|
|
|
|
def init_config():
|
|
"""初始化配置文件"""
|
|
print("加载配置文件...")
|
|
config = ReConfigParser()
|
|
try:
|
|
if os.getenv("FAST_API_ENV") == 'prod':
|
|
config.read(os.path.join('.', 'conf', 'conf-prod.ini'), encoding='utf-8')
|
|
else:
|
|
config.read(os.path.join('.', 'conf', 'conf-dev.ini'), encoding='utf-8')
|
|
# common_config = CommonConfig(**dict(config.items('common')))
|
|
mysql_config = MySQLConfig(**dict(config.items('mysql')))
|
|
print(mysql_config)
|
|
redis_config = RedisConfig(**dict(config.items('redis')))
|
|
return mysql_config, redis_config
|
|
except Exception as e:
|
|
print(e)
|
|
raise Exception("Config Error!")
|