51 lines
1.4 KiB
Python
51 lines
1.4 KiB
Python
import os
|
|
from configparser import ConfigParser
|
|
from typing import Optional
|
|
from pydantic import BaseModel
|
|
|
|
|
|
class ReConfigParser(ConfigParser):
|
|
def __init__(self, defaults=None):
|
|
ConfigParser.__init__(self, defaults=defaults)
|
|
|
|
"""复写方法实现key值区分大小写"""
|
|
def optionxform(self, optionstr):
|
|
return optionstr
|
|
|
|
|
|
class CommonConfig(BaseModel):
|
|
SECRET_KEY: str = os.urandom(32)
|
|
PROJECT_NAME: str
|
|
API_V1_STR: str
|
|
# 允许访问的origins
|
|
BACKEND_CORS_ORIGINS: str
|
|
|
|
|
|
class MySQLConfig(BaseModel):
|
|
USERNAME: str = None
|
|
PASSWORD: str = None
|
|
HOST: Optional[str] = "localhost"
|
|
PORT: Optional[int] = 3306
|
|
DATABASE: str = None
|
|
SQLALCHEMY_DATABASE_URI: str = (
|
|
f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOST}:{PORT}/{DATABASE}?charset=utf8"
|
|
)
|
|
|
|
|
|
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')
|
|
|
|
mysql_config = MySQLConfig(**dict(config.items('mysql')))
|
|
# common_config = CommonConfig(**dict(config.items('common')))
|
|
return mysql_config
|
|
except Exception as e:
|
|
print(e)
|
|
raise Exception("Config Error!")
|