Metadata-Version: 2.4
Name: tapp-safe
Version: 0.1.0
Summary: 安全的数学表达式计算器 - 基于 AST 解析的安全公式计算工具
Project-URL: Homepage, https://github.com/LH/tapp
Project-URL: Repository, https://github.com/LH/tapp.git
Project-URL: Documentation, https://github.com/LH/tapp#readme
Project-URL: Bug Tracker, https://github.com/LH/tapp/issues
Project-URL: Changelog, https://github.com/LH/tapp/blob/main/CHANGELOG.md
Author-email: LH <276069869@qq.com>
Maintainer-email: LH <276069869@qq.com>
License: MIT
Keywords: ast,calculator,expression,formula,math,safe-eval,安全计算,数学表达式,计算器
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Utilities
Requires-Python: >=3.13
Provides-Extra: dev
Requires-Dist: black>=23.0.0; extra == 'dev'
Requires-Dist: flake8>=6.0.0; extra == 'dev'
Requires-Dist: mypy>=1.0.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
Requires-Dist: pytest>=7.0.0; extra == 'dev'
Provides-Extra: test
Requires-Dist: pytest-cov>=4.0.0; extra == 'test'
Requires-Dist: pytest>=7.0.0; extra == 'test'
Description-Content-Type: text/markdown

# TApp-Safe - 安全的数学表达式计算器

[![Python Version](https://img.shields.io/badge/python-3.13+-blue.svg)](https://python.org)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Build Status](https://img.shields.io/badge/build-passing-brightgreen.svg)]()

TApp-Safe 是一个基于 AST（抽象语法树）解析的安全数学表达式计算器，专为需要安全执行用户输入的数学公式而设计。

## ✨ 特性

- 🔒 **安全性优先**：基于 AST 解析，只允许安全的数学运算
- 🧮 **支持基本运算**：加法、减法、乘法、除法、幂运算
- 📊 **变量支持**：支持自定义变量和动态计算
- 🎯 **精度控制**：自动保留小数点后两位
- 🚀 **简单易用**：提供函数式和面向对象两种使用方式
- 🛡️ **防注入攻击**：完全避免 `eval()` 的安全风险

## 🚀 快速开始

### 安装

使用 uv 安装（推荐）：

```bash
uv add tapp-safe
```

或者从源码安装：

```bash
git clone https://github.com/LH/tapp-safe.git
cd tapp-safe
uv sync
```

### 基本使用

#### 方法一：函数式调用

```python
from tapp.safe import calculate_metrics

# 定义变量
variables = {
    "aa": 10,
    "bb": 305,
    "cc": 1000,
    "dd": 65
}

# 计算表达式
result1 = calculate_metrics(variables, "aa / dd * 100")
print(f"结果: {result1}")  # 输出: 结果: 15.384615384615385

result2 = calculate_metrics(variables, "(bb + cc) / 100")
print(f"结果: {result2}")  # 输出: 结果: 13.05
```

#### 方法二：面向对象（推荐）

```python
from tapp.safe import MetricCalculator

# 创建计算器实例
calculator = MetricCalculator()

# 添加变量
calculator.add_metric("revenue", 10000)
calculator.add_metric("cost", 7500)
calculator.add_metric("tax_rate", 0.15)

# 计算利润率
profit_margin = calculator.calculate("(revenue - cost) / revenue * 100")
print(f"利润率: {profit_margin}%")  # 输出: 利润率: 25.0%

# 计算税后利润
after_tax_profit = calculator.calculate("(revenue - cost) * (1 - tax_rate)")
print(f"税后利润: {after_tax_profit}")  # 输出: 税后利润: 2125.0
```

## 📖 支持的运算符

| 运算符 | 说明 | 示例 |
|--------|------|------|
| `+` | 加法 | `a + b` |
| `-` | 减法 | `a - b` |
| `*` | 乘法 | `a * b` |
| `/` | 除法 | `a / b` |
| `**` | 幂运算 | `a ** 2` |
| `()` | 括号（优先级） | `(a + b) * c` |
| `+x` | 正号 | `+a` |
| `-x` | 负号 | `-a` |

## 🛡️ 安全特性

TApp 通过以下方式确保安全性：

1. **AST 解析**：使用 Python 的 `ast` 模块解析表达式，避免直接执行代码
2. **白名单机制**：只允许预定义的安全运算符
3. **变量隔离**：只能访问明确定义的变量
4. **无函数调用**：不允许执行任何函数或方法调用
5. **无导入语句**：完全禁止 import 语句

### 被阻止的危险操作

```python
# 以下操作都会被安全地拒绝：
calculator.calculate("__import__('os').system('rm -rf /')")  # ❌ 系统调用
calculator.calculate("eval('malicious_code')")              # ❌ eval 调用
calculator.calculate("open('/etc/passwd').read()")          # ❌ 文件操作
calculator.calculate("globals()")                           # ❌ 访问全局变量
```

## 🧪 运行测试

```bash
# 运行内置测试
uv run tapp

# 或者
uv run tapp-test
```

## 📁 项目结构

```
tapp/
├── src/
│   └── tapp/
│       ├── __init__.py
│       └── safe.py          # 核心计算模块
├── tests/                   # 测试文件（待添加）
├── pyproject.toml          # 项目配置
├── README.md               # 项目说明
└── LICENSE                 # 许可证
```

## 🔧 开发

### 开发环境设置

```bash
# 克隆项目
git clone https://github.com/LH/tapp.git
cd tapp

# 安装开发依赖
uv sync --extra dev

# 运行代码格式化
uv run black src/

# 运行类型检查
uv run mypy src/

# 运行测试
uv run pytest
```

### 贡献指南

1. Fork 本项目
2. 创建特性分支 (`git checkout -b feature/amazing-feature`)
3. 提交更改 (`git commit -m 'Add some amazing feature'`)
4. 推送到分支 (`git push origin feature/amazing-feature`)
5. 创建 Pull Request

## 📄 许可证

本项目采用 MIT 许可证 - 查看 [LICENSE](LICENSE) 文件了解详情。

## 🤝 支持

如果您遇到问题或有建议，请：

1. 查看 [Issues](https://github.com/LH/tapp/issues) 页面
2. 创建新的 Issue 描述问题
3. 或者发送邮件至：276069869@qq.com

## 📈 版本历史

- **v0.1.0** - 初始版本
  - 基本的安全表达式计算功能
  - 支持基本数学运算符
  - 提供函数式和面向对象两种接口

## 🎯 使用场景

TApp 特别适用于以下场景：

- 📊 **数据分析平台**：用户自定义计算指标
- 🏢 **企业报表系统**：动态公式计算
- 🎓 **在线教育平台**：数学表达式求值
- 🔬 **科学计算工具**：安全的公式执行
- 💼 **财务系统**：复杂的财务计算公式

---

⭐ 如果这个项目对您有帮助，请给我们一个 Star！