|
| 1 | +# /// script |
| 2 | +# requires-python = ">=3.11" |
| 3 | +# dependencies = ["pdfrest", "python-dotenv"] |
| 4 | +# /// |
| 5 | +"""Delete files with pdfRest's async client on Python 3.11+. |
| 6 | +
|
| 7 | +This sample shows how to: |
| 8 | +
|
| 9 | +1. Upload a local resource so we have a file id to delete. |
| 10 | +2. Delete that file successfully. |
| 11 | +3. Demonstrate how `PdfRestErrorGroup` behaves when we try to delete the same |
| 12 | + file again (Python 3.11 also allows `except* PdfRestDeleteError` if you want |
| 13 | + to tighten the example even further). |
| 14 | +
|
| 15 | +Run with `uv run --project ../.. python delete_example.py`; the script uses the |
| 16 | +checked-in `examples/resources/report.pdf` sample so no additional setup is |
| 17 | +required. |
| 18 | +""" |
| 19 | + |
| 20 | +from __future__ import annotations |
| 21 | + |
| 22 | +import asyncio |
| 23 | +from pathlib import Path |
| 24 | + |
| 25 | +from dotenv import load_dotenv |
| 26 | + |
| 27 | +from pdfrest import AsyncPdfRestClient, PdfRestDeleteError |
| 28 | + |
| 29 | +RESOURCE = Path(__file__).resolve().parents[1] / "resources" / "report.pdf" |
| 30 | + |
| 31 | + |
| 32 | +async def delete_with_except_star() -> None: |
| 33 | + load_dotenv() |
| 34 | + async with AsyncPdfRestClient() as client: |
| 35 | + uploaded = (await client.files.create_from_paths([RESOURCE]))[0] |
| 36 | + print(f"Uploaded {uploaded.name} with id={uploaded.id}") |
| 37 | + |
| 38 | + await client.files.delete(uploaded) |
| 39 | + print("First deletion succeeded.\n") |
| 40 | + |
| 41 | + print("Attempting to delete the same file again to trigger errors...") |
| 42 | + try: |
| 43 | + await client.files.delete(uploaded) |
| 44 | + except* PdfRestDeleteError as group: |
| 45 | + for error in group.exceptions: |
| 46 | + print(f"- Cleanup failed for {error.file_id}: {error.detail}") |
| 47 | + else: # pragma: no cover - would require server bug |
| 48 | + print("Second deletion unexpectedly succeeded.") |
| 49 | + |
| 50 | + |
| 51 | +if __name__ == "__main__": # pragma: no cover - manual example |
| 52 | + asyncio.run(delete_with_except_star()) |
0 commit comments