CloudLens 开发环境搭建与开发规范
最后更新:2025-12-23
git clone https://github.com/songqipeng/cloudlens.git
cd cloudlens
# 使用 venv
python3 -m venv .venv
# 激活虚拟环境
source .venv/bin/activate # Linux/Mac
# .venv\Scripts\activate # Windows
# 安装生产依赖
pip install -r requirements.txt
# 安装开发依赖
pip install -r requirements.txt
pip install pytest pytest-cov pytest-asyncio black flake8 mypy bandit pre-commit
cd web/frontend
# 安装依赖
npm install
# 启动开发服务器
npm run dev
# 创建配置目录
mkdir -p ~/.cloudlens
# 复制示例配置
cp config.json.example ~/.cloudlens/config.json
# 编辑配置
vim ~/.cloudlens/config.json
{
"accounts": [
{
"name": "test",
"alias": "测试账号",
"provider": "aliyun",
"region": "cn-beijing",
"access_key_id": "your_access_key_id",
"access_key_secret": "your_access_key_secret"
}
],
"database": {
"type": "sqlite",
"path": "data/db/cloudlens.db"
}
}
如果使用 MySQL,需要创建数据库:
CREATE DATABASE cloudlens CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
然后更新配置:
{
"database": {
"type": "mysql",
"host": "localhost",
"port": 3306,
"user": "root",
"password": "your_password",
"database": "cloudlens"
}
}
# 如果使用 MySQL,运行初始化脚本
mysql -u root -p cloudlens < sql/init_mysql_schema.sql
# 验证 Schema
python sql/verify_schema.py
cd web/backend
python -m uvicorn main:app --reload --port 8000
cd web/frontend
npm run dev
访问 http://localhost:3000 查看 Web 界面。
snake_case 命名函数和变量PascalCase 命名类# 格式化所有 Python 文件
black .
# 格式化特定文件
black core/idle_detector.py
# 检查格式(不修改)
black --check .
所有公共函数都应该包含类型提示:
from typing import List, Dict, Optional
def get_resources(
account: str,
resource_type: Optional[str] = None,
limit: int = 100
) -> List[Dict[str, Any]]:
"""
获取资源列表
Args:
account: 账号名称
resource_type: 资源类型(可选)
limit: 返回数量限制
Returns:
资源列表
"""
pass
使用 Google 风格的 Docstrings:
def calculate_cost(
resources: List[Dict],
start_date: datetime,
end_date: datetime
) -> float:
"""
计算指定时间范围内的资源成本
Args:
resources: 资源列表
start_date: 开始日期
end_date: 结束日期
Returns:
总成本(元)
Raises:
ValueError: 如果日期范围无效
"""
if start_date > end_date:
raise ValueError("开始日期不能晚于结束日期")
# ...
cd web/frontend
npm run lint
interface Resource {
id: string;
name: string;
type: string;
status: string;
cost: number;
}
function getResources(account: string): Promise<Resource[]> {
// ...
}
# 格式化代码
black .
# 检查代码风格
flake8 .
# 类型检查
mypy core providers
# 安全扫描
bandit -r core providers
使用 Conventional Commits 格式:
<type>(<scope>): <subject>
<body>
<footer>
feat: 新功能fix: Bug 修复docs: 文档更新style: 代码格式调整(不影响功能)refactor: 重构test: 测试相关chore: 构建/工具链更新# 新功能
git commit -m "feat(provider): add AWS provider support"
# Bug 修复
git commit -m "fix(cache): fix cache expiration issue"
# 文档更新
git commit -m "docs: update API reference"
# 重构
git commit -m "refactor(storage): unify storage interface"
git checkout -b feature/new-feature
git add .
git commit -m "feat: add new feature"
git push origin feature/new-feature
在 GitHub 上创建 Pull Request,填写:
Closes #123审查通过后,由维护者合并到主分支。
import pdb
def my_function():
pdb.set_trace() # 断点
# 代码会在这里暂停
pass
import logging
logger = logging.getLogger(__name__)
def my_function():
logger.debug("调试信息")
logger.info("一般信息")
logger.warning("警告信息")
logger.error("错误信息")
# 查看后端日志
tail -f logs/backend.log
# 查看前端日志
tail -f logs/frontend.log
console.log("调试信息", data);
console.error("错误信息", error);
console.warn("警告信息", warning);
# GET 请求
curl http://localhost:8000/api/accounts
# POST 请求
curl -X POST http://localhost:8000/api/budgets \
-H "Content-Type: application/json" \
-d '{"name": "测试预算", "amount": 1000}'
访问 http://localhost:8000/docs 进行交互式 API 测试。
# 查看数据库
sqlite3 data/db/cloudlens.db
# 执行查询
sqlite3 data/db/cloudlens.db "SELECT * FROM resources LIMIT 10;"
# 连接数据库
mysql -u root -p cloudlens
# 执行查询
mysql -u root -p cloudlens -e "SELECT * FROM resources LIMIT 10;"
问题:ModuleNotFoundError: No module named 'core'
解决方案:
# 确保在项目根目录
cd /path/to/cloudlens
# 确保虚拟环境已激活
source .venv/bin/activate
# 安装依赖
pip install -r requirements.txt
问题:OperationalError: unable to open database file
解决方案:
# 检查数据库文件路径
ls -la data/db/
# 创建目录
mkdir -p data/db
# 检查权限
chmod 755 data/db
问题:npm install 失败
解决方案:
# 清除缓存
rm -rf node_modules package-lock.json
# 重新安装
npm install
# 如果还有问题,尝试使用 yarn
yarn install
问题:API 请求超时
解决方案:
lib/api.ts)问题:数据没有更新
解决方案:
# 清除缓存
./cl cache clear
# 或使用 API
curl -X POST http://localhost:8000/api/virtual-tags/clear-cache
cloudlens/
├── core/ # 核心业务逻辑
│ ├── cache.py # 缓存管理
│ ├── config.py # 配置管理
│ ├── idle_detector.py # 闲置检测
│ └── ...
├── cli/ # CLI 命令
│ ├── main.py # CLI 入口
│ └── commands/ # 命令模块
├── web/ # Web 应用
│ ├── backend/ # FastAPI 后端
│ │ ├── main.py # 后端入口
│ │ └── api.py # API 路由
│ └── frontend/ # Next.js 前端
│ ├── app/ # 页面
│ └── components/ # 组件
├── providers/ # 云服务提供商
│ ├── aliyun/ # 阿里云
│ └── tencent/ # 腾讯云
├── resource_modules/ # 资源分析器
│ ├── ecs_analyzer.py
│ └── ...
├── tests/ # 测试
│ ├── core/ # 核心模块测试
│ └── providers/ # Provider 测试
└── docs/ # 文档
config.json: 主配置文件requirements.txt: Python 依赖pyproject.toml: Python 项目配置pytest.ini: 测试配置mypy.ini: 类型检查配置提交代码前,请确认:
docs/ 目录http://localhost:8000/docsHappy Coding! 🚀