frappex-client v0.1.1

Guides

Async client#

AsyncClient has exactly the same methods, arguments, return values and errors as Client. You await each call, use async with to open and close it, and async for to walk iter_list.

import asyncio
import os

from frappex_client import AsyncClient, TokenAuth


async def main() -> None:
    auth = TokenAuth(os.environ["ERP_KEY"], os.environ["ERP_SECRET"])
    async with AsyncClient(os.environ["ERP_URL"], auth) as client:
        print(await client.get_logged_user())
        async for row in client.iter_list("Customer", fields=["name"]):
            print(row["name"])


asyncio.run(main())
Sync Async
with Client(...) as client: async with AsyncClient(...) as client:
client.get_doc(...) await client.get_doc(...)
for row in client.iter_list(...) async for row in client.iter_list(...)
client.close() await client.aclose()

Both clients share one implementation of the Frappe API, so a fix or feature always lands in both. See Architecture.

Run requests concurrently#

One client can serve many concurrent requests over its connection pool:

async def load_orders(client, names):
    return await asyncio.gather(*(client.get_doc("Sales Order", name) for name in names))

Concurrency is fast but your ERP has limits. Cap it with a semaphore so a batch job does not overload the site or trip its rate limit:

limit = asyncio.Semaphore(8)


async def fetch(client, name):
    async with limit:
        return await client.get_doc("Sales Order", name)


orders = await asyncio.gather(*(fetch(client, n) for n in names))

Share one client in a web app#

Create the client once when the app starts and close it on shutdown. Creating a client per request throws away the connection pool and adds a TLS handshake to every call.

from contextlib import asynccontextmanager

from fastapi import FastAPI, HTTPException

from frappex_client import AsyncClient, NotFoundError, TokenAuth


@asynccontextmanager
async def lifespan(app: FastAPI):
    async with AsyncClient("https://erp.example.com", TokenAuth(KEY, SECRET)) as erp:
        app.state.erp = erp
        yield


app = FastAPI(lifespan=lifespan)


@app.get("/orders/{name}")
async def get_order(name: str):
    try:
        return await app.state.erp.get_doc("Sales Order", name)
    except NotFoundError:
        raise HTTPException(status_code=404, detail="Order not found") from None

Password sessions#

With PasswordAuth, the first request logs in. If several tasks start at the same moment, they wait for one shared login instead of each logging in.

Timeouts and cancellation#

Each request has a timeout (30 seconds by default). An asyncio timeout or task cancellation also stops a request cleanly:

async with asyncio.timeout(5):
    doc = await client.get_doc("Customer", "Acme Corporation")

Cancelling a write

If you cancel a task during an insert or update, the site may still have applied the change. Treat a cancelled write the same way as a TransportError: check before trying again.

Found a mistake? Open an issue.