Metadata-Version: 2.4
Name: pewutils
Version: 0.0.9
Summary: Lightweight utils for windmill scripts (migrated from peutils).
Author-email: rxu <rxu@appen.com>
License: MIT
Project-URL: Homepage, https://gitee.com/yunsansheng/pewutils
Keywords: pewutils,windmill,pe
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: oss2>=2.15
Requires-Dist: requests>=2.25
Requires-Dist: sqlalchemy>=2.0
Requires-Dist: psycopg2-binary>=2.9
Requires-Dist: pymysql>=1.1

# pewutils

PE Windmill Utils —— 为 Windmill 脚本平台提供的轻量级 Python 工具包。

由 `peutils` 迁移重构而来，适配 windmill 脚本平台。

## 已迁移模块

| 模块 | 说明 | 依赖 |
|------|------|------|
| `url_util` | URL 处理工具（解析、存储 URL、签名 URL 清理、查询参数等） | 仅标准库 |
| `oss_util` | 阿里云 OSS 工具（STS 鉴权、列举、复制、搜索） | oss2, requests |
| `db_util` | 通用数据库连接工具（SQLAlchemy 封装，增删查改/事务/流式查询） | sqlalchemy, psycopg2-binary, pymysql |
| `wmill_util` | Windmill 平台工具（zip 打包上传 S3） | wmill（windmill runtime 内置） |

## 安装

```bash
# 默认安装全部所需依赖（含 sqlalchemy 与 PG/MySQL 驱动）
pip install pewutils

# 本地开发（editable）
git clone <repo-url> pewutils
cd pewutils
pip install -e .
```

## 使用示例

### URL 工具

```python
from pewutils.url_util import (
    get_clean_url,
    parse_storage_url,
    parse_oss_full_path,
    get_relative_path,
)

# 去除 OSS 签名 URL 的查询参数
clean = get_clean_url("https://bucket.aliyuncs.com/path/file.pcd?Expires=123&Signature=xxx")
# -> "https://bucket.aliyuncs.com/path/file.pcd"

# 解析存储 URL（宽松）
bucket, path = parse_storage_url("oss://my-bucket/folder/file.txt")
# -> ("my-bucket", "folder/file.txt")

# 解析 OSS 目录路径（强约束，要求以 / 结尾）
bucket, folder = parse_oss_full_path("oss://my-bucket/folder/")
```

### OSS 工具

```python
from pewutils.oss_util import OSSClientFactory

# 创建带自动刷新的 OSS client（auth_str 12h 过期，11h 自动刷新）
client = OSSClientFactory.create_client(bucket_name="my-bucket")

# 读取 OSS 对象为字节流
data = client.read_bytes("path/to/file.pcd")

# 列举目录下所有文件
files = client.list_bucket_files_deep("path/to/folder/")

# BFS 查找最浅的目标文件
path = client.find_shallowest_target("root/", "target.json", "file")
```

### 数据库工具

> sqlalchemy 与 PostgreSQL/MySQL 驱动已包含在默认依赖中，
> Windmill 脚本直接 `from pewutils.db_util import DbClient` 即可，无需写 `# requirements:`。

```python
from pewutils.db_util import DbClient

db_setting = {"user": "u", "pwd": "p", "host": "127.0.0.1", "port": 5432}
with DbClient(db_setting, dbname="mydb") as db:
    # 原生 SQL 查询（参数走绑定变量）
    rows = db.query("select id, name from t where id = :id", {"id": 1})
    user = db.query_one("select * from users where id = :id", {"id": 1})
    total = db.query_scalar("select count(*) from users")

    # 字典驱动 CRUD（免手写 SQL，表名/列名自动校验防注入）
    db.insert("users", [{"name": "a"}, {"name": "b"}])
    ids = db.insert("users", {"name": "c"}, returning="id")
    db.update("users", {"status": 0}, where={"id": 1})
    users = db.select("users", where={"status": 1}, order_by="id desc", limit=10)
    db.delete("users", where={"status": 0})

    # 事务：块内操作同一事务，异常自动回滚
    with db.transaction():
        db.execute("update a set x = 1 where id = :id", {"id": 2})
        db.insert("b", {"y": 2})

    # 大表流式遍历，不一次性载入内存
    for row in db.stream("select * from big_table"):
        process(row)
```

### Windmill 平台工具

```python
from pewutils.wmill_util import zip_to_s3

# with 块内生成文件，退出时自动打包 zip 上传到 Windmill S3
with zip_to_s3("output/zip", suffix=".json") as out:
    Path("a.json").write_text('{"k": 1}')
    Path("b.json").write_text('{"k": 2}')
# out.result -> S3Object(s3="output/zip/20260729/uuid.zip")
# out.files  -> [Path("a.json"), Path("b.json")]
```

## 目录结构

```
pewutils/
├── README.md
├── pyproject.toml              # 打包配置（PEP 517/518，requires-python>=3.10）
├── .gitignore
└── pewutils/
    ├── __init__.py             # 默认导出轻量模块（base/url_util/text_util/datetime_util）
    ├── base.py                 # 通用数据结构（DotDict，纯标准库）
    ├── url_util.py             # URL 处理（纯标准库）
    ├── text_util.py            # 文本处理（纯标准库）
    ├── datetime_util.py        # 时间处理（纯标准库）
    ├── oss_util.py             # OSS 工具（oss2, requests）
    ├── db_util.py              # 数据库工具（sqlalchemy + psycopg2-binary + pymysql）
    └── wmill_util.py           # Windmill 平台工具（wmill lazy import）
```

## 构建

```bash
pip install build
python -m build
# 产物：dist/pewutils-<version>-py3-none-any.whl
```
