python(62) : 环境变量管理

1.说明

优先加载当前目录的".env"文件, ".env"格式如下:

bash 复制代码
# 应用配置
APP_NAME=我的APP
APP_VERSION=1.0.0
DEBUG=True

# 服务器配置
HOST=0.0.0.0
PORT=8001
TIMEOUT=30

# 日志配置
CONSOLE_LOG_LEVEL=DEBUG

2.python代码(config.py)

python 复制代码
import os
import sys

# pip install python-dotenv
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()


class Settings:
    def __init__(self):
        # 应用配置
        self.app_name = os.getenv("APP_NAME", "FastAPI App")
        self.app_version = os.getenv("APP_VERSION", "1.0.0")
        self.debug = os.getenv("DEBUG", "False").lower() == "true"

        # 服务器配置
        self.host = os.getenv("HOST", "0.0.0.0")
        self.port = int(os.getenv("PORT", 8001))
        self.timeout = int(os.getenv("TIMEOUT", 30))

        # MySQL配置
        self.mysql_host = os.getenv("MYSQL_HOST", "127.0.0.1")
        self.mysql_port = int(os.getenv("MYSQL_PORT", "3306"))
        self.mysql_user = os.getenv("MYSQL_USER", "root")
        self.mysql_password = os.getenv("MYSQL_PASSWORD", "123456")
        self.mysql_database = os.getenv("MYSQL_DATABASE", "test")
        self.mysql_charset = os.getenv("MYSQL_CHARSET", "utf8mb4")

        # MySQL连接池配置
        self.mysql_pool_size = int(os.getenv("MYSQL_POOL_SIZE", "10"))
        self.mysql_max_overflow = int(os.getenv("MYSQL_MAX_OVERFLOW", "20"))
        self.mysql_pool_timeout = int(os.getenv("MYSQL_POOL_TIMEOUT", "30"))
        self.mysql_pool_recycle = int(os.getenv("MYSQL_POOL_RECYCLE", "3600"))


settings = Settings()

3.使用

python 复制代码
import settings

pring(settings.app_name)
相关推荐
吴佳浩20 小时前
GPU 编号进阶:CUDA\_VISIBLE\_DEVICES、多进程与容器化陷阱
人工智能·pytorch·python
全栈凯哥21 小时前
18.Python中的导入类完全指南
python
sunwenjian88621 小时前
Java进阶——IO 流
java·开发语言·python
guts3501 天前
图像篡改数据集下载:COVERAGE、CASIA
python·数据集
森林猿1 天前
java-modbus-读取-modbus4j
java·网络·python
2401_879693871 天前
将Python Web应用部署到服务器(Docker + Nginx)
jvm·数据库·python
chushiyunen1 天前
python chatTts实现tts文本转语音、音频
python
FreakStudio1 天前
把 Flask 搬进 ESP32,高中生自研嵌入式 Web 框架 MicroFlask !
python·单片机·嵌入式·cortex-m3·异步编程·电子diy
love530love1 天前
OpenClaw 手机直连配置全流程
人工智能·windows·python·智能手机·c#·agent·openclaw
chushiyunen1 天前
python中的内置属性 todo
开发语言·javascript·python