feat: 添加 .env 环境变量支持

- 创建 .env.example 模板文件
- 添加 load_env.py 自动加载 .env 文件
- 更新 .gitignore 忽略 .env 文件
- 更新 README.md 添加配置说明
- translate_excel.py 自动加载 .env 文件
This commit is contained in:
ivanberry 2026-03-11 20:06:47 +08:00
parent 8d7ce43819
commit e5e2ce9671
4 changed files with 91 additions and 0 deletions

8
.env.example Normal file
View File

@ -0,0 +1,8 @@
# Gemini API Key 配置
# 获取 API Key: https://aistudio.google.com/app/apikey
# 方式 1: 使用 Gemini API Key推荐
GEMINI_API_KEY=your-api-key-here
# 方式 2: 使用 Google API Key备选
# GOOGLE_API_KEY=your-google-api-key-here

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
# Environment variables (contains secrets)
.env
.env.local
*.env

View File

@ -541,3 +541,35 @@ pyproject.toml 已包含镜像配置:
[tool.uv]
index-url = "https://pypi.tuna.tsinghua.edu.cn/simple"
```
## 环境变量配置
### 方式 1: 使用 .env 文件(推荐)
在项目根目录创建 `.env` 文件:
```bash
# .env
GEMINI_API_KEY=your-api-key-here
```
脚本会自动加载 `.env` 文件中的环境变量。
**注意**: `.env` 文件已添加到 `.gitignore`,不会被提交到 git。
### 方式 2: 命令行设置
```bash
export GEMINI_API_KEY="your-api-key"
uv run python scripts/translate_excel.py --file data.xlsx
```
### 方式 3: 命令行参数
```bash
uv run python scripts/translate_excel.py --file data.xlsx --api-key your-api-key
```
### 获取 API Key
访问https://aistudio.google.com/app/apikey

46
scripts/load_env.py Normal file
View File

@ -0,0 +1,46 @@
#!/usr/bin/env python3
"""
.env 文件加载环境变量
"""
import os
from pathlib import Path
def load_env(env_path: Path | None = None) -> None:
"""
.env 文件加载环境变量
Args:
env_path: .env 文件路径默认当前目录的 .env
"""
if env_path is None:
# 查找 .env 文件
possible_paths = [
Path(".env"),
Path(__file__).parent.parent / ".env",
Path.cwd() / ".env",
]
for p in possible_paths:
if p.exists():
env_path = p
break
if not env_path or not env_path.exists():
return # 没有 .env 文件,跳过
print(f"📄 加载环境变量:{env_path}")
with open(env_path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
# 跳过空行和注释
if not line or line.startswith("#"):
continue
# 解析 KEY=VALUE
if "=" in line:
key, value = line.split("=", 1)
key = key.strip()
value = value.strip()
# 只设置尚未存在的环境变量
if key not in os.environ:
os.environ[key] = value
print(f"{key} = {value[:10]}...")