Skip to main content

安全的数学表达式计算器 - 基于 AST 解析的安全公式计算工具

Project description

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

Python Version License Build Status

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

✨ 特性

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

🚀 快速开始

安装

使用 uv 安装(推荐):

uv add tapp-safe

或者从源码安装:

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

基本使用

方法一:函数式调用

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

方法二:面向对象(推荐)

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 语句

被阻止的危险操作

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

🧪 运行测试

# 运行内置测试
uv run tapp

# 或者
uv run tapp-test

📁 项目结构

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

🔧 开发

开发环境设置

# 克隆项目
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 文件了解详情。

🤝 支持

如果您遇到问题或有建议,请:

  1. 查看 Issues 页面
  2. 创建新的 Issue 描述问题
  3. 或者发送邮件至:276069869@qq.com

📈 版本历史

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

🎯 使用场景

TApp 特别适用于以下场景:

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

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tapp_safe-0.1.0.tar.gz (5.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tapp_safe-0.1.0-py3-none-any.whl (5.5 kB view details)

Uploaded Python 3

File details

Details for the file tapp_safe-0.1.0.tar.gz.

File metadata

  • Download URL: tapp_safe-0.1.0.tar.gz
  • Upload date:
  • Size: 5.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.7.8

File hashes

Hashes for tapp_safe-0.1.0.tar.gz
Algorithm Hash digest
SHA256 0bc13fdd8cf4fa26f0a727ddec886d195c0d27fb856c5582caa951318d7070da
MD5 dfb1ed7e3cb83bf5b35e4ded14d7da98
BLAKE2b-256 8f702122d29caf0a85d12ee3a0ffff90989fccee414b3095a81a99762da7ef89

See more details on using hashes here.

File details

Details for the file tapp_safe-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: tapp_safe-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 5.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.7.8

File hashes

Hashes for tapp_safe-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ffd10c4c755566ec2bb3c096b7543ad599ba809a860a41b339a3f5ce2346967a
MD5 0284f445a5c523802e57a21ccda3be16
BLAKE2b-256 8820ce1f15108ff2a3c88a122d7c88548040059b008a51220143ab99ee515a6e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page