quilletcms
The Python read client for Quillet's delivery API.
It fetches published content, keeps private files behind your own server, and renders
{{ variables }} and Markdown to safe HTML, from sync code (classic Django views, management
commands, templates) and from async code (FastAPI, async Django views) alike. It is the Python
sibling of the JavaScript SDK, @quilletcms/sdk, and
reads the same configuration file and environment variables.
Install
pip install quilletcms
Python 3.11 or later. The core needs no web framework. quilletcms.django needs Django 5.2 or
later (pip install "quilletcms[django]"), and quilletcms.fastapi needs Starlette or FastAPI
(pip install "quilletcms[fastapi]", which installs Starlette).
Configure
Non-secret settings live in .quilletrc (JSON, safe to commit) at your project root:
{ "apiUrl": "https://cms.example.com", "project": "marketing-site", "assets": { "path": "/media" } }
The key id and secret come from environment variables or from code — a key in the config file
is refused. The environment is QUILLET_ENV, which overrides an env the file may carry as a
local default:
QUILLET_ENV=prod
QUILLET_KEY_ID=app_… # a delivery key from the Keys page
QUILLET_KEY_SECRET=…
The file keeps the camelCase keys it shares with the JavaScript SDK and the Quillet CLI. Every
setting: apiUrl, project, env, locale, refs (0–5, default 3), cache.ttl (seconds,
default 0 = revalidate every read), assets.mode (proxy | signed), assets.path (/media),
assets.proxyPublic (false), assets.maxAge (300), retry.attempts (2). Any string may hold
${VAR}, read from the environment. An unknown key is refused; the CLI's own sync key is
accepted and left alone. The file is QUILLET_CONFIG (a path, which must exist) when that is
set, else the first .quilletrc or .quilletrc.json found walking up from the working
directory. The environment variables QUILLET_API_URL, QUILLET_PROJECT, QUILLET_ENV,
QUILLET_LOCALE, QUILLET_KEY_ID and QUILLET_KEY_SECRET are read too.
In Python the same settings are snake_case keyword arguments. Code overrides the environment,
the environment overrides the file, the file overrides the defaults:
from quilletcms import AsyncQuillet, Quillet
site = Quillet() # the file and the environment
staging = Quillet(env="staging", cache_ttl=60) # code wins
proxied = Quillet(assets={"proxy_public": True}) # assets: mode, path, proxy_public, max_age
german = AsyncQuillet(locale="de-DE", retry_attempts=0)
The keywords are api_url, project, env, locale, refs, key_id, key_secret,
cache_ttl, assets and retry_attempts. An assets= mapping is merged over the file's asset
settings field by field; an AssetsConfig replaces them all. The values are validated together,
and every problem is reported in one ConfigError; an invalid api_url is never echoed back,
since a mistyped ${…} could have made it a secret. A problem with the file itself — it cannot
be read, is not a JSON object, holds a key or an unknown key, or names a ${VAR} that is unset
or refused — stops the reading at once and is reported alone.
The secret is kept out of sight:
- The file may not hold a
key, and may not substitute ${QUILLET_KEY_ID},
${QUILLET_KEY_SECRET} or ${QUILLET_MANAGEMENT_KEY}: credentials are read from the
environment (or your code) directly.
- The resolved configuration is a frozen dataclass,
client.config. Its repr leaves out
key_secret, and client.config.public_dict() is every setting but the secret, as plain values —
use that to log or show a configuration. dataclasses.asdict(client.config) includes the
secret.
- No error message,
details or log line carries the secret: it is redacted from what the API
answers.
A client owns an httpx client. Create one per process (an AsyncQuillet per event loop) and
reuse it; close() / await aclose(), or with / async with, releases it. Pass your own
httpx.Client / httpx.AsyncClient as http_client= for timeouts, proxies or a test transport;
the SDK then leaves it open. Quillet.from_config(load_config(...)) builds a client from a
configuration resolved beforehand.
Read
Create the clients once, at module level, and reuse them; the samples below use these two:
from quilletcms import AsyncQuillet, Quillet
q = Quillet()
aq = AsyncQuillet()
hero = q.get("landing/hero", locale="de-DE", vars={"user_name": "Ada"})
nav = q.list("docs/", depth=2)
tree = q.tree("docs/")
for entry in q.walk("docs/"):
print(entry.item.title, entry.document.content) # build a page per document
The async client has the same methods with the same arguments. Its reads — get, list,
search, lake, tree — are coroutines, and walk is an async iterator; render_markdown,
invalidate and the assets helpers are plain calls on both clients:
async def pages() -> None:
hero = await aq.get("landing/hero")
async for entry in aq.walk("docs/"):
print(entry.item.key, entry.document.meta.version)
A client used for one job only can be closed when it is done:
with Quillet() as once:
print(once.get("landing/hero").meta.version)
get returns a Document: key, locale, type, content and meta. content is the body
exactly as the CMS sent it — a dict, list or str — so a template reads
{{ doc.content.title }} without help. meta is the API's _meta under a name a Django
template can reach: resolved_locale (which locale answered), fallback_locale and fallbacks
(what fell back to it), version, published_at, content_hash, refs and refs_truncated
(the references followed), assets and assets_truncated (the assets reached), and preview.
Timestamps stay the ISO strings the API sent.
get takes locale, at (a timezone-aware datetime, sent as UTC, or a string), preview,
refs (how many levels of references to follow, 0–5), vars and missing. locale and refs
default to the configuration.
list returns a Listing of items without bodies — prefix, locale, folder, folders,
items — one level below the prefix unless you give it a depth; it takes locale, at,
preview, depth and tags. walk fetches every document under a prefix at any depth, four at
a time (concurrency=), and yields a WalkEntry of item and document in listing order; give
it a depth to stop sooner. It takes the list options plus refs, concurrency, vars and
missing, and an error is raised at the entry it belongs to. tree nests a prefix's folders and
items into a FolderNode (path, title, description, order, items, children); like
walk it covers the whole subtree unless you give it a depth, and every node's path is free
of a trailing slash — tree("docs/") answers docs, tree("") answers "". Children sort by
order (a folder with none last), then by path.
A key, prefix or lake name is checked against the CMS's grammar before any request is spent; a
bad one raises a QuilletError with code invalid_key, invalid_prefix or
invalid_lake_name. The grammars are exported as KEY_PATTERN, PREFIX_PATTERN and
LAKE_NAME_PATTERN.
Each client keeps an in-memory cache of up to 1000 answers, one per request URL. With
cache_ttl 0 every read revalidates with If-None-Match, and a 304 is answered from the
cache; with a cache_ttl an answer younger than that is served without a request. Reads with
at or preview are never cached, and vars are applied after the cache, so your values never
enter it. Every value you are handed is your own copy. q.invalidate(key) drops one key (and
every cached lake), q.invalidate() everything; cache=None turns the cache off. Answers 429
and 503 are retried retry_attempts times, waiting Retry-After when sent, else 250 ms
doubling, capped at five seconds.
Search
answer = q.search("promotion", prefix="docs/", tags=["guide"], limit=5)
for hit in answer.hits:
href = f"/{hit.key}#{hit.anchor}" if hit.anchor else f"/{hit.key}"
search asks one environment's published content. q is required, 1 to 200 characters,
and Mongo's own grammar works inside it — "a phrase" and -excluded. There is no fuzzy
matching and no prefix matching: promot does not find promotion. The options are locale
(the configured one by default), prefix (slash-terminated, and checked before any request),
tags (a document must carry every one), limit (1–50, 10 by default) and offset (0-based).
There is no at and no preview: the API refuses both.
The answer is a SearchResult of hits, total and meta (q, locale, limit, offset).
A SearchHit names the document (key, title), the heading the answer was found under and
that heading's anchor, the fragment to append to the page's URL. heading and anchor are
None together, on a hit about the page as a whole. snippet is plain text with no markup
at all: mark the terms yourself. score is comparable within one answer and meaningless across
two — sort by it, but do not threshold on it. locale is the locale the text was written in, and
fallback_locale is set only where the key had nothing in the locale you asked for and the
project's default answered instead.
Paging stops at the first 200 results: offset + limit may not exceed 200, and total is the
size of that window rather than of the whole match set. An answer is cached like a listing. A
project with search turned off answers 404, which arrives as a NotFoundError.
Data lakes
copy = q.lake("site", locale="uk-UA", vars={"name": "Ada"})
copy.fields["done"] # "Готово"
copy.fields["errors"]["card-declined"] # "Картку відхилено"
copy.fields["page"]["home"]["title"] # "Вітаємо, Ada!"
copy.meta.fields["errors.card-declined"] # LakeFieldMeta(key='errors/card-declined', ...)
errors = copy.fields["errors"] # a branch is a plain dict: hand it to the template that shows it
A data lake is a named set of copies the CMS serves as one file, in the locale asked for, falling
back field by field to the default. A lake's field is a path — dotted segments, prefilled from
the copy's key (errors/card-declined → errors.card-declined). fields is the nested
dictionary those paths make: a group is a dict holding its own paths, a leaf what get would
answer as content with refs=0 (a string for text and md, the merged object for json),
or None when its copy has nothing published there or in the default locale, or does not exist.
Segments keep the key's spelling (card-declined). A lake whose paths are all one segment is the
flat dict it always was. The order of the fields carries no meaning.
meta.fields stays flat, keyed by the full path. A path present there is a copy, which is how a
site tells a json copy from a group; missing is True for a None leaf.
meta.assets[]["path"] runs through the groups (page.home.hero.image).
vars and asset URLs apply at every depth; a missing variable is reported against
_lakes/<name> at its full path (errors.card-declined).
Options are locale (the configured one by default), vars and missing, which apply to every
string of every field as they do in get. There is no at, preview or refs. The name is one
key segment, checked before any request. A lake is cached like a document, and
q.invalidate(key) drops every cached lake as well as key, since any copy may sit in any lake.
Preview drafts
get, list, tree and walk all take a preview token, minted by the Quillet dashboard's
Preview on website button for one document, locale and fifteen minutes. A site's own preview
route receives the token as a query parameter, uses it to read the one document it names, and —
once it has checked the request is genuinely the reader who was sent it — keeps it in a cookie
for the length of the visit:
draft = q.get("docs/intro", locale="en-US", preview=token)
draft.meta.preview # True
A preview read is never cached. list and walk pass the token to every request they make, so
an unpublished document under a listed prefix appears in a walk's results, with
meta.published_at None if it has never been published. Passing at and preview together
is refused by the CMS with 422; the SDK forwards what it is given. Minting and verifying a token
is the CMS's and your preview route's concern — this package only carries the string. Hold it no
longer than the preview needs, in an httpOnly cookie your route controls.
Private files
Every asset in a document's content arrives as the dictionary the API delivered, with url
(what to render) and originUrl (what the API answered) — the wire's spelling, since it sits
among wire fields. By default a private file's url points at your own site, /media/<id>, and
you mount the proxy there. A public file's url stays the CMS's own delivery URL; set
assets.proxyPublic (proxy_public=True in code) to serve public files through your host as
well, so every image is same-origin. Set assets.mode to signed to skip the proxy: url is
then the API's own signed URL. A private file the delivery key may not read arrives with url
(and originUrl) None; asset_url then answers None and srcset answers "".
from quilletcms import asset_url, signed_url, srcset
image = hero.content["image"]
asset_url(image, w=640, f="webp") # url with ?w=640&f=webp
srcset(image) # "<url>?w=320 320w, <url>?w=640 640w, …"
signed_url(image) # originUrl: the API's own URL, signed for a private file
q.assets.srcset(image, widths=[320, 640], format="webp")
The proxy streams bytes from Quillet with your delivery key, so the reader never sees Quillet's
host or a token; the delivery key must hold the assets:private scope. It answers GET and
HEAD; passes w and f through, and Range, If-None-Match and If-Range; answers 200,
206, 304 and 416 with an allow-list of the upstream's headers; turns 401, 403 and 404 into a bare
404, so a reader cannot tell "no right to it" from "no such file"; and answers anything else with
a 502, logged once per status through the quilletcms logger. Cache-Control is the upstream's
when public, else private, max-age=<assets.maxAge>. A malformed id answers 404 without asking
the CMS.
Who may see a private file is your site's decision: check the reader's session before the
proxy runs — a FastAPI dependency, a Django decorator.
One prerequisite on the CMS side: proxying a private file needs a Quillet CMS at or after
quilletcms/quillet-cms#5, which lets the
bytes route open a private file for a delivery key holding assets:private. On an older CMS a
private file answers 404 through the proxy, and assets.mode: "signed" is the option that works
there.
FastAPI and Starlette
from fastapi import FastAPI
from quilletcms import AsyncQuillet
from quilletcms.fastapi import asset_route
aq = AsyncQuillet()
app = FastAPI()
app.add_api_route("/media/{asset_id}", asset_route(aq), methods=["GET", "HEAD"])
asset_route(client) returns an async endpoint that takes a Starlette Request. A file is
streamed; the answers without a body (HEAD, 304, 404, 405, 502) are plain responses. It needs
an AsyncQuillet, so the event loop is never blocked; given a Quillet it raises TypeError
when the route is made. Registered
with methods=["GET", "HEAD"], other methods get the router's own 405. It uses only Starlette,
so it mounts in a plain Starlette app too:
Route("/media/{asset_id}", asset_route(aq), methods=["GET", "HEAD"]). Guard it with your own
dependency (dependencies=[Depends(...)]).
Django
# urls.py
from django.urls import path
from quilletcms.django import asset_view
urlpatterns = [path("media/<str:asset_id>", asset_view())]