Real-world recipes#
Each recipe is a complete pattern you can copy and adapt. They all read credentials from the environment:
import os
from frappex_client import Client, TokenAuth
auth = TokenAuth(os.environ["ERP_KEY"], os.environ["ERP_SECRET"])
erp = Client(os.environ["ERP_URL"], auth)
Sync another system into ERPNext#
A webshop, CRM or signup form creates customers. Run this for each record it sends you: it creates the customer the first time and updates it afterwards.
from frappex_client import ValidationError
def sync_customer(erp, record):
values = {
"customer_name": record["company"],
"customer_type": "Company",
"customer_group": "Commercial",
"territory": "All Territories",
"email_id": record["email"],
}
existing = erp.get_value("Customer", "name", {"email_id": record["email"]})
try:
if existing:
return erp.update("Customer", existing["name"], values)
return erp.insert("Customer", values)
except ValidationError as error:
raise RuntimeError(f"ERP rejected {record['email']}: {error.server_messages}") from error
Why it works:
get_valuereturnsNoneinstead of raising when nothing matches, so the lookup is a plainif.ValidationErrorcarries the exact field the site complained about.- If the process crashes and runs again, the lookup finds the customer created last time, so re-running is safe.
Serve ERP data from FastAPI#
Share one AsyncClient for the life of the service, and translate frappex-client
errors into HTTP responses:
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from frappex_client import AsyncClient, NotFoundError, PermissionDeniedError, TokenAuth
@asynccontextmanager
async def lifespan(app: FastAPI):
auth = TokenAuth(os.environ["ERP_KEY"], os.environ["ERP_SECRET"])
async with AsyncClient(os.environ["ERP_URL"], auth, timeout=10) as erp:
app.state.erp = erp
yield
app = FastAPI(lifespan=lifespan)
@app.get("/customers/{name}/orders")
async def customer_orders(name: str):
erp = app.state.erp
try:
await erp.get_doc("Customer", name)
except NotFoundError:
raise HTTPException(404, "No such customer") from None
except PermissionDeniedError:
raise HTTPException(403, "Not allowed") from None
return await erp.get_list(
"Sales Order",
fields=["name", "transaction_date", "grand_total", "status"],
filters={"customer": name, "docstatus": 1},
order_by="transaction_date desc",
limit=50,
)
Export data to CSV#
Stream every row straight to a file, without holding the whole table in memory:
import csv
fields = ["name", "customer_name", "customer_group", "territory", "creation"]
with open("customers.csv", "w", newline="", encoding="utf-8") as out:
writer = csv.DictWriter(out, fieldnames=fields, extrasaction="ignore")
writer.writeheader()
for row in erp.iter_list("Customer", fields=fields, page_size=500):
writer.writerow(row)
CSV injection
A cell that starts with =, +, - or @ runs as a formula when the
file is opened in a spreadsheet. If people will open the export in Excel,
prefix such values with a single quote.
Run scheduled jobs#
A nightly job that closes stale ToDos. It is safe to run twice, logs what it did, and stops cleanly on errors:
import logging
from datetime import date, timedelta
from frappex_client import Client, FrappexError, TokenAuth
log = logging.getLogger("close_stale_todos")
def close_stale_todos(erp, days=30):
cutoff = (date.today() - timedelta(days=days)).isoformat()
closed = 0
stale = list(
erp.iter_list(
"ToDo",
fields=["name"],
filters={"status": "Open", "modified": ["<", cutoff]},
)
)
for row in stale:
try:
erp.update("ToDo", row["name"], {"status": "Closed"})
closed += 1
except FrappexError:
log.exception("Could not close %s", row["name"])
log.info("Closed %d of %d stale ToDos", closed, len(stale))
The rows are collected with list(...) before any update, because updating a
row while paging over the same filter would change the result set mid-walk.
Monitor a site#
A health check needs no credentials. Use a short timeout and no retries so a slow site is reported quickly:
from frappex_client import Client, FrappexError, RetryPolicy
def site_is_healthy(url: str) -> bool:
try:
with Client(url, timeout=5, retry=RetryPolicy(max_attempts=1)) as site:
return site.ping() == "pong"
except FrappexError:
return False
Bulk import with limited concurrency#
Create many records quickly with the async client, at most eight at a time, and collect failures instead of stopping at the first one:
import asyncio
from frappex_client import AsyncClient, FrappexError
async def import_items(erp: AsyncClient, items: list[dict]) -> list[tuple[str, str]]:
limit = asyncio.Semaphore(8)
failures: list[tuple[str, str]] = []
async def create(item: dict) -> None:
async with limit:
try:
await erp.insert("Item", item)
except FrappexError as error:
failures.append((item["item_code"], str(error)))
await asyncio.gather(*(create(item) for item in items))
return failures
Attach generated documents#
Generate a PDF in your own system and attach it to the matching record:
def attach_contract(erp, customer: str, pdf: bytes) -> str:
file_doc = erp.upload_file(
f"contract-{customer}.pdf",
pdf,
doctype="Customer",
docname=customer,
)
return file_doc["file_url"]
The file is private, so only users who can read the customer can download it.
Call your app from a Discord or Slack bot#
Bots are async programs; give the bot one AsyncClient and call your own
whitelisted methods:
async def handle_command(erp, order_name: str) -> str:
status = await erp.get_value("Sales Order", ["status", "grand_total"], order_name)
if status is None:
return f"Order {order_name} not found"
return f"{order_name}: {status['status']}, total {status['grand_total']}"