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)
相关推荐
孟健8 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞10 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽12 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
阿巴斯甜16 小时前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android
Kapaseker16 小时前
实战 Compose 中的 IntrinsicSize
android·kotlin
敏编程17 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪17 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook17 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
xq952717 小时前
Andorid Google 登录接入文档
android
黄林晴19 小时前
告别 Modifier 地狱,Compose 样式系统要变天了
android·android jetpack