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)
相关推荐
matrixmind19 小时前
aiomysql:异步场景下的 MySQL 驱动
android·数据库·mysql·其他
财经资讯数据_灵砚智能9 小时前
基于全球经济类多源新闻的NLP情感分析与数据可视化(夜间-次晨)2026年6月11日
人工智能·python·ai·信息可视化·自然语言处理·ai编程·灵砚智能
随遇丿而安9 小时前
第8周:弹窗 / 提示组件全功能与弹窗优化
android
zh_xuan9 小时前
诡异Bug:输入框删除字符,却越删越多
android·bug
CC数学建模9 小时前
2026年第十六届APMCM 亚太地区大学生数学建模竞赛(中文赛项)赛题C题:创业社区规划与资源配置优化问题完整思路、代码、模型、文章,全网首发高质量分享!
python·算法·数学建模
2601_956139429 小时前
性价比高的VI设计质量
大数据·人工智能·python·物联网
右耳朵猫AI9 小时前
Python周刊2026W23 | Polars 1.41、PyPy v7.3.23、Python 3.15、httpx2、dj-lite-tenant
开发语言·python
garmin Chen9 小时前
prompt实战:nof1.ai Alpha Arena
java·人工智能·python·prompt
装不满的克莱因瓶9 小时前
掌握条件生成对抗网络(Conditional GAN)模型结构——从无条件生成到可控生成的进阶
人工智能·pytorch·python·深度学习·神经网络·生成对抗网络·计算机视觉
菜鸟小九9 小时前
hello agent(智能体经典范式、框架开发实践)
python·langchain·agent