首页 > 其他分享 >FastAPI 读取不同环境的配置文件

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

时间:2023-03-08 18:14:20浏览次数:37  
标签:读取 配置文件 get FastAPI self SETTING path config dir

配置文件

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()

标签:读取,配置文件,get,FastAPI,self,SETTING,path,config,dir
From: https://www.cnblogs.com/pgyLang/p/17195617.html

相关文章

  • python FastAPI sqlalchemy 数据库模型基类通用模型
    作用用于所有表都需要使用的字段或者方法实现代码base.py#!/usr/bin/python#-*-coding:utf-8-*-#@time:2023/2/1317:43#@author:pugongying#@de......
  • FastAPI log日志插件配置
    #!/usr/bin/python#-*-coding:utf-8-*-#@time:2023/2/315:21#@author:pugongying#@description:日志配置#获取日志目录importloggingimporto......
  • FastAPI 启动事件 tart_event(),停止事件shutdown_event()
    作用需要在应用程序启动之前或者关闭时进行,例如数据库迁移,定时任务·····实际代码main.pyimportuvicornfromappimportcreate_appapp=create_app()if......
  • Django 实现Canal 读取 MySQL 写入到 Kafka中
    安装canal-python库:pipinstallcanal-python修改settings.py文件,添加Canal相关配置CANAL_SETTINGS={"canal_host":"127.0.0.1","canal_port":11111,......
  • Go语言: 如何让 request.Body 可以多次读取
    起因:困惑使用了go的http服务后,发现request.Body居然只能读取一次,第二次读取数据为nil.比如我在gin的服务器中,先加入了accessLog,需要进行parseForm()但是后续......
  • js读取href中的参数函数
    functionGetQueryValue(queryName){ varquery=decodeURI(window.location.search.substring(1)); varvars=query.split("&"); for(vari=0;i<vars.lengt......
  • FastAPI - Get
    fromfastapiimportFastAPIimportuvicornapp=FastAPI()#默认接口文档http://127.0.0.1:8000/docs@app.get("/")defindex():  '''这是首页'''  return"this......
  • FastAPI -Post
    fromfastapiimportFastAPIimportuvicornapp=FastAPI()#仅支持POST@app.post("/login1")deflogin():  return{"msg:loginsuccess1"}#支持POST,GET,PUT@app.ap......
  • FastAPI - Parameter
    fromfastapiimportFastAPIimportuvicornapp=FastAPI()#访问方式:http://127.0.0.1:8000/user?id=888@app.get("/user")defuser(id):       #id为接......
  • spring源码02-xml配置文件解析过程
    本文主要讲解spring通过xml进行配置时对xml的加载和解析过程、自定义标签的处理,重点是流程,不说明详细细节;一、创建ClassPathXmlApplicationContext对象//创建容器,并启动......