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)
相关推荐
vvoennvv5 小时前
【Python TensorFlow】 TCN-LSTM时间序列卷积长短期记忆神经网络时序预测算法(附代码)
python·神经网络·机器学习·tensorflow·lstm·tcn
4***99745 小时前
Kotlin序列处理
android·开发语言·kotlin
t***D2645 小时前
Kotlin在服务端开发中的生态建设
android·开发语言·kotlin
nix.gnehc5 小时前
PyTorch
人工智能·pytorch·python
玲珑Felone5 小时前
flutter 状态管理--InheritedWidget、Provider原理解析
android·flutter·ios
BoomHe5 小时前
车载应用配置系统签名
android·android studio
z***3356 小时前
SQL Server2022版+SSMS安装教程(保姆级)
后端·python·flask
I'm Jie6 小时前
从零开始学习 TOML,配置文件的新选择
python·properties·yaml·toml
二川bro6 小时前
Scikit-learn全流程指南:Python机器学习项目实战
python·机器学习·scikit-learn
代码的乐趣6 小时前
支持selenium的chrome driver更新到142.0.7444.175
chrome·python·selenium