|
| 1 | +"""Create, fetch, update, and delete a Template with the async client. |
| 2 | +
|
| 3 | +Run from the repository root: |
| 4 | +
|
| 5 | + TRANSLOADIT_KEY=xxx TRANSLOADIT_SECRET=yyy poetry run python examples/async_template_lifecycle.py |
| 6 | +""" |
| 7 | + |
| 8 | +import asyncio |
| 9 | +import os |
| 10 | +from uuid import uuid4 |
| 11 | + |
| 12 | +from transloadit.async_client import AsyncTransloadit |
| 13 | + |
| 14 | + |
| 15 | +def get_credentials(): |
| 16 | + key = os.getenv("TRANSLOADIT_KEY") |
| 17 | + secret = os.getenv("TRANSLOADIT_SECRET") |
| 18 | + if not key or not secret: |
| 19 | + raise RuntimeError("Please set TRANSLOADIT_KEY and TRANSLOADIT_SECRET.") |
| 20 | + return key, secret |
| 21 | + |
| 22 | + |
| 23 | +def extract_template_id(response_data): |
| 24 | + template_id = response_data.get("id") or response_data.get("template_id") |
| 25 | + if not template_id: |
| 26 | + raise RuntimeError(f"Template response did not contain an id: {response_data}") |
| 27 | + return template_id |
| 28 | + |
| 29 | + |
| 30 | +async def main(): |
| 31 | + key, secret = get_credentials() |
| 32 | + template_id = None |
| 33 | + deleted = False |
| 34 | + template_name = f"python-sdk-async-example-{uuid4().hex[:12]}" |
| 35 | + |
| 36 | + async with AsyncTransloadit(key, secret) as client: |
| 37 | + try: |
| 38 | + template = client.new_template(template_name) |
| 39 | + template.add_step( |
| 40 | + "resize", |
| 41 | + "/image/resize", |
| 42 | + { |
| 43 | + "use": ":original", |
| 44 | + "width": 120, |
| 45 | + "height": 120, |
| 46 | + "resize_strategy": "fit", |
| 47 | + "format": "png", |
| 48 | + }, |
| 49 | + ) |
| 50 | + created = await template.create() |
| 51 | + template_id = extract_template_id(created.data) |
| 52 | + print("Created template:", template_id) |
| 53 | + |
| 54 | + fetched = await client.get_template(template_id) |
| 55 | + print("Fetched template:", fetched.data.get("name") or fetched.data.get("template_name")) |
| 56 | + |
| 57 | + updated = await client.update_template( |
| 58 | + template_id, |
| 59 | + { |
| 60 | + "name": f"{template_name}-updated", |
| 61 | + "template": { |
| 62 | + "steps": { |
| 63 | + "resize": { |
| 64 | + "use": ":original", |
| 65 | + "robot": "/image/resize", |
| 66 | + "width": 96, |
| 67 | + "height": 96, |
| 68 | + "resize_strategy": "fit", |
| 69 | + "format": "jpg", |
| 70 | + }, |
| 71 | + }, |
| 72 | + }, |
| 73 | + }, |
| 74 | + ) |
| 75 | + print("Updated template:", updated.data.get("ok")) |
| 76 | + |
| 77 | + deleted_response = await client.delete_template(template_id) |
| 78 | + print("Deleted template:", deleted_response.data.get("ok")) |
| 79 | + deleted = True |
| 80 | + finally: |
| 81 | + if template_id and not deleted: |
| 82 | + await client.delete_template(template_id) |
| 83 | + |
| 84 | + |
| 85 | +if __name__ == "__main__": |
| 86 | + asyncio.run(main()) |
0 commit comments