KptnCook
A small command line client for downloading KptnCook recipes, including today’s picks, discovery screens and lists,
dailies, onboarding tags, and ingredient-based searches. It can also sync
to Mealie and export recipes to Paprika, Tandoor, or Markdown.
Thanks to this blogpost for the url to get the json for today’s recipes.
It’s in pre alpha status and currently slightly unmaintained. If you want to step in, please let me know.
Disclaimer
This is an unofficial tool. It is not affiliated with, endorsed by, or
supported by KptnCook. “KptnCook” is used only to describe which service the
tool works with.
- It talks to KptnCook’s undocumented mobile API, which can change or stop
working at any time.
- It is meant for personal use, such as backing up your own favorites into
your own recipe manager. Recipe texts and images remain the property of
their rights holders; do not republish them.
- You are responsible for how you use it, including complying with
KptnCook’s terms of service.
Maintenance disclosure
This repository is maintained with substantial assistance from coding agents.
Most routine implementation, investigation, documentation, triage, and
release-preparation work may be performed through agent-assisted workflows.
Changes are still reviewed and accepted by the maintainer, and human
contributors are welcome.
Dependencies
- Python >=3.10
- Mealie >=v1.0
Installation
$ uvx install kptncook
Docker
Build the image from this repository:
$ docker build -t kptncook .
The container sets KPTNCOOK_HOME=/data. Mount that directory and provide the
required environment variables. Passing configuration with -e is the
recommended approach for Docker: it avoids the need for an interactive setup and
works the same on every run. For Mealie auth, set MEALIE_API_TOKEN or
MEALIE_USERNAME/MEALIE_PASSWORD:
$ docker run --rm -v ~/.kptncook:/data \
-e KPTNCOOK_API_KEY=6q7QNKy-oIgk-IMuWisJ-jfN7s6 \
-e MEALIE_URL=https://mealie.example.com/api \
-e MEALIE_USERNAME=user \
-e MEALIE_PASSWORD=pass \
kptncook sync
Alternatively, set MEALIE_API_TOKEN=... instead of MEALIE_USERNAME and
MEALIE_PASSWORD.
To back up favorites, also set KPTNCOOK_ACCESS_TOKEN:
$ docker run --rm -v ~/.kptncook:/data \
-e KPTNCOOK_API_KEY=... \
-e KPTNCOOK_ACCESS_TOKEN=... \
-e MEALIE_URL=https://mealie.example.com/api \
-e MEALIE_USERNAME=user \
-e MEALIE_PASSWORD=pass \
kptncook backup-favorites
The guided setup is available as the kptncook setup subcommand, so it is
reachable through the container’s kptncook entrypoint. Because it prompts for
your KptnCook account credentials, run it with an interactive TTY (-it). The
.env it writes lives at $KPTNCOOK_HOME/.env (i.e. /data/.env), so the
mounted volume persists it across runs:
$ docker run --rm -it -v ~/.kptncook:/data kptncook setup
To fetch only the access token after the API key is already configured, use
docker run --rm -it -v ~/.kptncook:/data kptncook kptncook-access-token.
Usage
help
Usage: kptncook [OPTIONS] COMMAND [ARGS]...
Options:
--install-completion [bash|zsh|fish|powershell|pwsh]
Install completion for the specified
shell.
--show-completion [bash|zsh|fish|powershell|pwsh]
Show completion for the specified shell,
to copy it or customize the installation.
--help Show this message and exit.
Commands:
backup-favorites Store kptncook favorites in local repository.
dailies List daily recipes from the kptncook site.
delete-recipes Delete recipes from the local repository.
discovery-list List recipes from a discovery list.
discovery-screen List discovery screen lists and quick search entries.
ingredients-popular List popular ingredients.
kptncook-access-token Fetch and save the KptnCook access token.
kptncook-today List all recipes for today from the kptncook...
list-recipes List all locally saved recipes.
onboarding List onboarding recipes by tags.
recipes-with-ingredients List recipes that match ingredient ids.
save-todays-recipes Save recipes for today from kptncook site.
search-by-id Search for a recipe by id in kptncook api, id...
sync Fetch recipes for today from api, save them to...
sync-with-mealie Sync locally saved recipes with mealie.
export-recipes-to-paprika Export a recipe by id or all recipes to Paprika app
export-recipes-to-tandoor Export a recipe by id or all recipes to Tandoor
export-recipes-to-markdown Export a recipe by id or all recipes to Markdown files
Recipe IDs can be short share UIDs or 24 ASCII hexadecimal characters (case
insensitive). Recognized KptnCook recipe share URLs use the UID or OID in the
final path segment, with its original case. Query strings and fragments can
accompany the link. A malformed identifier on a recognized share route is
reported as an invalid share URL by the CLI, without searching the other URL
segments for an ID. In other pasted text, short UIDs take precedence over
OIDs when both are present.
Local single-recipe exports to Paprika, Tandoor and Markdown accept either the
stored short UID or OID (including parsed recipe URLs). A missing selector
match or multiple matching recipes produces an error; selection never fetches
from the network.
Selected OID/UID lookups read one raw repository snapshot and validate full
recipe models only for matching identities. Warnings concern malformed matching
records and retain their original store positions; unrelated malformed recipes
are reported by full listings/exports instead. The raw JSON store is still read
and checked in full, including its number and text checks and duplicate-OID
admission policy.
Repository library calls that log skipped rows still return the valid recipes
if a logging handler fails to deliver a warning.
If closing the KptnCook client fails after backup-favorites saves, the CLI
prints the completed counts and a short cleanup warning, then exits with status
- The backup remains saved and needs no replay. Library callers receive the
counts and a
cleanup_warning even if a log handler fails. If the backup
itself fails, its primary error still reaches the caller. The workflow tries
to log the cleanup warning in either case.
When a recipe or discovery read fails, the CLI reports the original error,
even if closing the client also fails. A close failure after a successful
read reports KptnCook client cleanup failed. and exits with status 1.
search-by-id behaves like backup-favorites: after a close failure that
follows a successful save it prints the added recipe and the cleanup warning,
then exits with status 1. The recipe remains saved.
When a library API client’s context exits after an operation error, a failure
to close its owned HTTP client produces a short warning and the original error
reaches the caller. A standalone close failure propagates to the caller.
Injected HTTP clients remain open for their owners to close.
Library API clients send requests only to their configured HTTP(S) origin
(scheme, host and effective port), with no userinfo in the URL. Relative paths
and same-origin absolute URLs are supported, including an explicit default
port. Cross-origin requests are refused before transport. The Host header is
derived from the admitted URL and takes precedence over any Host value set on
the wrapper, the individual request, or the injected HTTPX client. Automatic
redirects are disabled even for injected HTTPX clients; requesting
follow_redirects=True is refused. Follow an intended Location explicitly
through the API client so it receives the same origin check.
Configure API base URLs, including MEALIE_URL, without a query or fragment.
Relative endpoints retain the base path, such as /proxy/mealie/api behind a
reverse proxy.
Every KptnCook JSON response rejects duplicate object members at any depth and
nonfinite JSON constants before interpreting tokens, identities or discovery
fields. Decoder errors report only “KptnCook returned an unreadable response.”
and contain no response fragments, member names or keyed URLs.
If today’s recipe list cannot be decoded or contains a non-object entry,
kptncook-today, save-todays-recipes and sync report a short error without
response details. A refused list leaves the local recipe store unchanged
and stops sync before contacting Mealie.
Before recipe models are built, today’s recipes, dailies, resolved search results
and selected restored recipes must fit a recipe envelope. Each recipe may use 32
container levels, 262,144 visited values/keys and 8,388,608 text characters
(including keys and ignored metadata); a real recipe needs about 7,000 values/keys.
A whole batch may hold 4,096 recipes, 33,554,432 values/keys and 67,108,864 text
characters; the value/key and text totals cover any store within the 64 MiB
store limit, while stores with more than 4,096 recipes are refused. The same
walk checks keys and string values for Unicode surrogate code points and accepts
supplementary characters such as emoji. Cycles, overflow or surrogate code
points cause the whole batch to be refused before a favorites backup or export
starts. Selected local lookups apply the envelope to matching records; full
listings apply it to the complete set. These expanded-model limits are separate
from the envelope-search limits below.
Each recipe in a resolved search response receives the same local import date.
The client reads the date once after accepting the response.
Favorites and discovery-list envelope searches allow at most 16 dictionary
levels and 4,096 work units per response (each visited value or supported-key
probe costs one unit). Traversal is iterative, detects active dictionary cycles
for library inputs and stops before resolving or saving a backup on refusal.
Recipe lists are leaves, so this budget applies to finding the list, not its
records. For discovery-list endpoint responses, a top-level list selected by
key precedence is accepted even when empty. In nested wrappers, the search
continues through the remaining recognized aliases after an empty list,
including dictionaries nested under those aliases.
The discovery-screen presentation path also uses iterative traversal, limited
to 16 dictionary levels and 4,096 visited-value/key-probe operations per list
search (lists and quick search). Cycles, depth and work overflow produce a short
malformed-screen error with no partial listing; localized text, key precedence
and entry order are retained. Screen entry lists are leaves for these searches.
For lists and quick search, each dictionary uses its first nonempty supported
list alias. If all its list aliases are empty, the search skips that dictionary’s
children and continues with its siblings. An explicit empty list at the root
ends that search when the root has no nonempty alias.
Localized discovery titles and quick-search labels skip empty and whitespace-only
translations in the usual key order and preserve the selected text verbatim.
A list with only blank title translations is shown without a title if it has an
ID or type. Quick search checks the aliases title, name, label, text
and query for nonblank strings in that order, then tries localized text in
localizedTitle and title. Blank standalone labels and entries without a
usable label are omitted.
Before constructing summaries, the complete screen must also fit 4,096 raw
entries across the selected lists and quick-search leaves (including entries
that would be ignored), and 262,144 characters across all displayed IDs, titles,
list types and quick-search labels. Displayed fields must contain valid Unicode
scalar text. Supplementary characters such as emoji are supported. Exceeding
either limit or encountering a surrogate code point in a displayed field
refuses the whole screen with a short error.
Share URLs are resolved using only the response headers, without reading bodies
or following redirects. Only 301/302 responses with a Location are accepted.
Resolution has a 15-second elapsed budget; a reply observed after it is discarded
before recipe lookup or storage. HTTPX socket timeouts are capped by the remaining
budget (connect at most 5 seconds); in-flight I/O follows HTTPX’s per-operation
timeout rules. Transport diagnostics do not include the share URL or secrets.
Quick examples
Short snippets for the new discovery/dailies/onboarding/ingredient commands
(see the detailed sections below for flag descriptions):
$ kptncook discovery-screen
$ kptncook discovery-screen --no-quick-search
$ kptncook discovery-list --list-type latest
$ kptncook discovery-list --list-type recommended
$ kptncook discovery-list --list-type curated --list-id 12345
$ kptncook discovery-list --list-type automated --list-id 67890
$ kptncook dailies --recipe-filter veggie --save
$ kptncook onboarding --tag rt:diet_vegetarian
$ kptncook onboarding --tag "low-carb,high-protein" --save
$ kptncook ingredients-popular
$ kptncook recipes-with-ingredients --ingredient-id 123,456 --save
Mealie sync
sync-with-mealie (and sync) creates every locally saved recipe that is not
yet in Mealie. Recipes are matched by the KptnCook id stored in the Mealie
recipe’s extras (source: kptncook), not by name. A native ZIP import creates
the complete recipe with those identity extras already present. Distinct
KptnCook recipes with the same title can both be imported: Mealie assigns a
unique name and slug, which subsequent updates preserve.
Once Mealie acknowledges a creation, later rows with the same KptnCook ID are
skipped in that run. A failed attempt is reported separately and also prevents
another attempt for that ID in the same run. When the outcome is unknown, the
next sync checks the remote inventory before deciding whether to create it.
Ctrl-C during Mealie sync reports confirmed creations, failed attempts and the
KptnCook ID of any in-progress import whose outcome remains unverified. The
next sync checks the remote inventory before creating recipes. Library callers
can read the mealie_sync_progress receipt on the original KeyboardInterrupt.
Each Mealie recipe conversion uses one settings snapshot for its translations,
ingredient grouping, image host allowlist and default KptnCook API key.
A settings reload can affect the next recipe. Missing translations use the
usual fallback, and library callers can supply an explicit image API key.
Ingredient names are split at the first comma only: the food name precedes it,
and the complete remaining preparation note retains subsequent commas and
internal whitespace, with outer whitespace trimmed. Grouping and locale fallback
remain unchanged.
Step-media URL components are percent-encoded and the final HTML attribute is
escaped, so server-returned filenames remain data. Server-returned instruction
markup is preserved during image enrichment; source step HTML is escaped as
literal text before import. Conversion DEBUG logs contain only recipe identity
and counts;
cover and nested step image URLs (including API keys) are never logged there.
With logging enabled, the request lines of httpx and httpcore’s DEBUG trace
show [REDACTED] in place of API keys, tokens, URL credentials and secret
header values. A failed KptnCook request (for example an HTTP 500 during
kptncook-today, save-todays-recipes or sync) ends with a short
HTTP <status> while ... or Request failed: <category> error, never with a
traceback naming the keyed request URL, and tracebacks never show local
variables on any supported Typer release (typer >= 0.6).
Mealie recipe slugs are admitted as single route components: nonempty Unicode
letters/numbers, hyphens and underscores only, percent-encoded when building
requests. Slash, backslash, dot segments, percent escapes, query/fragment
separators and controls are refused before authenticated follow-up requests.
An archive receipt must be a valid slug, and its detail reply must carry that
exact slug and a valid server recipe UUID before any media request. Matching
source extras alone do not establish route identity. Step-image PATCH replies
must retain the imported slug, UUID and identity extras; a mismatched reply keeps
the known core import result and emits a media warning without retry or deletion.
Step photos are uploaded only when the imported instructions have exactly the
same unique texts in the same order as the source. Missing, inserted, reordered
or repeated texts omit all step photos with a bounded warning, retaining the
imported text recipe and server-assigned instruction fields.
Cover and step images are best-effort follow-ups. The client keeps the core
import receipt and continues eligible media work even when logging a warning
fails. Step uploads use the downloaded JPEG, PNG or WebP signature for both
the Mealie extension and the multipart filename. Unsupported step images are
skipped with a warning. Step-image updates patch only the instructions.
Immediately before the instruction PATCH, the client re-reads recipe identity
and the complete instruction list. Changes to text, IDs, order, references or
other instruction fields during asset uploads skip enrichment with a warning.
Uploaded assets may remain unused. There is still a server race between this
GET and PATCH: the checked Mealie
v1.12
and v3.28
PATCH routes expose no conditional revision/ETag contract. An ambiguous PATCH
is never retried, and human edits are never rolled back. The PATCH response
must confirm each new image reference on the expected step, using server
step IDs when available. A missing or ambiguous acknowledgement produces a
media warning and preserves the original import receipt.
The summary means:
Created N recipes: recipes newly created in Mealie.
Failed to sync N recipes: each line names the recipe, its KptnCook id and
the reason (HTTP status, connection error, timeout or local processing
error). Other recipes are still synced, and the command exits with status 1.
Name-collision errors are failures, not successful identity matches.
Local processing failures appear as Local processing error (<exception class>)
in sync results, CLI output and logs. These diagnostics omit exception messages,
which may contain recipe values.
The sync continues and retains its summary if a logging handler fails to deliver
a recipe or cleanup warning.
Client cleanup is attempted once even after a failed or interrupted sync. A lock
release or client close failure preserves the primary error or the result’s created/failed
counts. A completed result carries a separate cleanup_warning; the CLI displays
it alongside those counts and exits with status 1. The count-only library wrapper
also reports the warning with completed counts. Cleanup failure does not undo
imports or trigger replay; reconcile unknown outcomes through the next sync’s
identity inventory. Cleanup diagnostics omit exception messages and URLs.
Cooperating sync processes on this machine hold one advisory lock across the
complete inventory and create sequence. The lock covers all accounts on the same
canonical Mealie API target (host casing, default ports and trailing slashes are
normalized), including rotated tokens. Locks are per operating-system user,
independent of KPTNCOOK_HOME, under ~/.cache/kptncook/sync-locks/. Keep these
stable files while syncs may be running. Lock admission refuses symlinks,
special files (including FIFOs), hardlinks, nonprivate permissions and files
owned by another user, and verifies the named inode again after acquisition.
It never repairs or replaces an unsafe lock file. An uncooperative process
replacing lock names after admission is outside this advisory lock contract. A competing sync waits for the current
owner to finish for at most 30 seconds, then reports that sync is busy. Retry after
the current sync finishes. Timeout or interruption closes the authenticated client
without reading or modifying recipes. Lock admission errors stop sync before
inventory. This does not coordinate different machines or
manual Mealie clients and does not promise exactly-once delivery.
An organizer POST that returns Mealie’s explicit uniqueness response (409 with
detail.message equal to This item already exists.) triggers one inventory
refresh. A single matching organizer ID is reused (casefolded for tags, exact
names for foods/units). Ambiguous or absent matches, generic conflicts, legacy
400 responses and transport failures remain failures; the POST is never retried.
A successful organizer POST with the expected name but no ID also triggers one
read-only inventory refresh. The recipe archive is submitted only if that
refresh finds one matching organizer with a valid ID. Existing matches
without IDs also stop the recipe before import.
Units, foods and tags are listed once per sync, not once per recipe. The lookup
is built only from a complete inventory and then updated with organizers this
sync created (or found through an inventory refresh). Each name’s inventory
matches stay in listing order, with repeated IDs counted once and each entry
without an ID counted separately. Each new sync, login or token change reads
Mealie again. A recipe creation failure retires the
cached organizer inventories: the next independent recipe rereads them, allowing
remotely removed/recreated organizers to recover. The failed recipe/import is
never automatically replayed. If several existing organizers with
different IDs match one requested name (for example tags Vegan and vegan),
that recipe fails before any unit, food, tag or recipe is created, naming the
ambiguous organizer. Merge or rename the duplicates in Mealie, then sync again;
kptncook never deletes or merges remote organizers.
A timeout or malformed response may occur after Mealie committed the import.
The client does not retry or delete the recipe after such an ambiguous result.
Run the sync again: it first checks stored identity extras and skips any
recipe already imported. Do not delete a recipe merely because its import
response was lost.
Image downloads for Paprika and Tandoor covers, Markdown images and Mealie step assets are
limited to 10 MiB per image and 60 seconds for the entire transfer (including
redirects). Failed, oversized, or slow images are skipped; recipe text is
still exported or imported. Downloads request uncompressed responses; servers
that send compressed images despite that request are skipped to bound memory.
The final response must be HTTP 200 without a Content-Range header. Other
statuses and responses carrying range metadata are refused before reading the body.
A declared Content-Length must be valid and within the per-image limit before
streaming begins. An image is attached only when the body is nonempty and its
byte count matches any declared length.
The API key is attached only to image URLs on an allowed image host: HTTPS,
the default port, no user name or password in the URL, and a host name that
exactly matches one of KptnCook’s image hosts (d2am1qai33sroc.cloudfront.net,
images.kptncook.com) or an entry in KPTNCOOK_IMAGE_HOSTS. Every redirect
target is checked the same way before it is requested. Images from any other
URL in recipe data are skipped with a warning that names neither the URL nor
the key; recipe text is still exported or imported. Mealie covers are downloaded through the same
checked downloader and uploaded as image bytes; Mealie is never asked to fetch
a keyed URL itself, since its scraper would follow redirects unchecked.
The downloaded JPEG, PNG or WebP signature determines both the cover filename
and the upload extension, including after redirects. An unrecognized format
is skipped and the imported recipe remains in Mealie.
Configured hosts must be names, not IP addresses in any spelling.
The image downloader requires direct HTTPS access to the allowed hosts. It
ignores HTTPX environment settings for proxies and CA certificates, including
HTTPS_PROXY, ALL_PROXY, SSL_CERT_FILE and SSL_CERT_DIR.
Deployments that require a forward proxy will skip images if direct access is
unavailable. Recipe image response and client close failures are reported as
short warnings. The transfer result still reflects the received body and its
validation, and a valid redirect can still be followed.
Sync requires a complete, validated remote recipe inventory, including every
recipe detail. An invalid recipe or unreadable imported identity stops the run
before any organizer or archive creates, with a bounded positional diagnostic.
Check the indicated upstream record and rerun; invalid records are never silently skipped.
Each recipe detail must describe the inventory row it was requested for: the
same server ID (when the row carries one) and the requested slug. A detail for a
different recipe, or a recipe renamed while the inventory is read, stops the run
before any write; run the sync again to read a consistent inventory.
Recipe and organizer inventories allow at most 1,000 pages and 50,000 items.
Listing pages and sync detail responses are streamed as uncompressed JSON.
Each page or detail may use up to 8 MiB, with at most 64 MiB across all
pages of one listing. An oversized or compressed response stops acquisition
before it can be used for creates.
Sync starts one monotonic deadline before pagination and shares it with
every recipe page and detail read. The default budget is 120 seconds.
The client caps request timeouts by the remaining budget and checks again
after headers, between body chunks and before accepting the inventory.
If a chunk arrives after the deadline, the client closes the response
without reading the rest. A blocking HTTPX operation can still take up
to its socket timeout.
Large libraries with sequential detail reads may need a larger budget: set
MEALIE_INVENTORY_TIMEOUT_SECONDS=7200, for example. This setting must be finite,
positive and at most 86,400 seconds. Rerunning a library that consistently exceeds
its budget needs a larger setting. Library users can pass inventory_timeout=
to MealieApiClient without loading KptnCook settings.
Changing totals, mismatched reported counts/page numbers, repeated identities and
empty pages in a multi-page inventory abort the acquisition before writes.
Mealie organizer pages must contain a list of objects and a nonnegative integer
total_pages (zero is allowed only for an empty inventory). Invalid pages abort
listing before organizer creation. Successful password login requires a nonempty
string token; malformed replies leave any existing authorization unchanged.
Mealie control JSON refuses duplicate object member names, including escaped
spellings of the same name, and nonfinite numbers at every nesting level before
identity checks or follow-up requests. Nonfinite numbers include NaN,
Infinity, -Infinity and numbers that overflow floating-point conversion.
This applies to login, inventories/details, import, organizer and media
responses, version discovery, PATCH replies and conflict details.
Repeated values in arrays remain valid. Decode failures use fixed diagnostics
without response fragments, member names or tokens; existing error-body limits
and inventory budgets still apply. A malformed response after a write does not
cause a retry or rollback.
Library callers own healthy clients returned by get_mealie_client() and should
close them or use a context manager. Failed authentication closes the new client.
Sync, favorites backup, login, today/dailies, discovery, onboarding, ingredient
queries and recipe search close their own clients on success and every failure;
closing a wrapper around a borrowed HTTPX client keeps that shared client usable.
Request headers with the same exact key override wrapper defaults. An explicit
per-request timeout takes precedence over an explicit BaseHttpClient
timeout, which takes precedence over the borrowed HTTPX client’s timeout.
Without either override, a borrowed client keeps its configured timeout and an
owned client uses 10 seconds for connect and 30 seconds for read, write and
pool waits. tests/client_ownership_test.py checks these on real HTTPX requests
with a synthetic transport, including exceptional context exits.
Exports to Mealie and Tandoor include KptnCook active tags verbatim. Tandoor
keeps the first occurrence of each exact keyword name, in order from the
kptncook keyword through the active tags to the recipe type. Spelling and
case are preserved. Mealie keeps the first occurrence of each exact source tag
name in archive order and substitutes the server tag record using a
case-insensitive lookup.
All exporters preserve the recipe’s explicit fixedPortionCount, falling back
to the standard two portions when it is absent. KptnCook stores ingredient
quantities for a single serving, also for fixed-portion recipes such as a batch
of cookies, so exporters scale them to the portion count they write. Explicit
portion counts must be positive integers (no booleans or coercion). Ingredient and step-ingredient quantities
must be finite, and their scaled results must also be representable as finite
floats. This includes step ingredients and Markdown --servings overrides.
Overflow is refused with a bounded field location before image downloads, file
publication or remote creates. Export batches are preflighted before writes;
previous exports remain intact. Zero, fractions and missing quantities remain
supported, with the same six-decimal rounding across adapters.
Whole-recipe preparation and cooking times are strict integer minutes from 0 to
525600 (365 days); booleans, strings and fractional values are refused.
Preparation time is required. Missing/null cooking time stays unknown; explicit
zero stays zero in every exporter. Each step timer endpoint is optional and must
be a strict integer in the same 0 to 525600 minute range when present. The
maximum must be at least the minimum when both are present.
Exact/zero, max-only and ranged timers are retained without
mutating source lists. Invalid numeric recipes are reported through the existing
invalid-stored-entry warnings and excluded from export/import.
Tandoor and Markdown use numeric servings,
Paprika uses a decimal string, and Mealie uses the string <count> Portionen.
Markdown front-matter string values are quoted as YAML scalars,
so punctuation and newlines in tags and URLs retain their string values.
Tags are normalized and deduplicated in first-occurrence order, with the
vegan tag first for recipes of type Vegan.
Front matter uses tags: [] when no display tags remain after filtering.
The Markdown export (export-recipes-to-markdown) writes one .md file per
recipe into an export_md directory under the KptnCook home, with YAML front
matter (full title, export date, servings, prep/cook time, link, image, tags)
followed by ingredients and instructions. All notes in a batch use the local
date at the start of the export. The output allowance counts the same UTF-8
bytes written to staging. Images are downloaded into its sibling assets/ directory
with random filenames and relative references; copy that directory along with
the notes. The downloaded byte signature determines the extension (.jpg,
.png, or .webp). Markdown tries the final step image first. If its URL is
missing or disallowed, the download fails, or the signature is unrecognized,
Markdown tries the recipe cover when exactly one is available and its URL is
distinct. Both downloads share the batch asset allowance. Exhaustion stops
the batch. If neither image is usable, the note contains the recipe text
without image metadata or markup. Authentication keys and signed image URLs
appear only in download requests and are omitted from notes and asset names.
Library render_recipe() performs no image I/O and omits images unless passed
an explicit local image_path. It defaults to the current local date unless an
export_date is supplied. Image authentication preserves existing query
pairs/fragments and replaces any old kptnkey value.
Section headings and image alt text follow KPTNCOOK_LANG
(German, English, Spanish, French, and Portuguese are recognized; other
languages fall back to English). Recipe titles, comments, steps and ingredient
labels across all exporters prefer that same configured language. Missing,
empty and whitespace-only translations fall back in order to German, English,
Spanish, French, then Portuguese. A usable translation retains its surrounding
whitespace. For legacy variant maps, the first map in singular, plural,
uncountable order with a nonblank translation in a supported language is
used. Direct language maps and plain strings are also accepted.
<timer> placeholders in steps are replaced with their durations.
If a timer is missing or has no duration metadata,
the placeholder and its punctuation stay in every export: Paprika keeps the
literal <timer>, while the rendered Markdown, Tandoor and Mealie step texts
write it as the code span `<timer>` so renderers show it instead of
hiding it as an HTML tag. Later timers keep their positions; no duration is
invented.
Raw HTML in source steps is not supported formatting: Markdown, Tandoor and
Mealie escape source &, < and > before inserting trusted timer text or
visible unresolved markers. Literal tags and angle-bracket instructions therefore
remain visible and inert; other Markdown syntax still follows the destination
renderer. Because escaping covers the whole step, &, < and > inside a
source code span (and existing HTML entities such as &) render as their
escaped text, for example `a<b` shows as a<b. Paprika’s plain-text directions retain literal source characters.
Check the source recipe for unresolved timing instructions before cooking.
Markdown is final cookbook text, so its serving count is configurable:
kptncook export-recipes-to-markdown --servings 4 (or -s 4) scales standard
recipes to four servings instead of two. Recipes with a fixed portion count
keep that count. The servings front matter shows the count the quantities
were scaled to. Paprika and Markdown retain all admitted scaled decimal places
(up to six), including tiny nonzero kg/l quantities, without exponent notation.
Zero quantities remain omitted from ingredient text. All three file exporters
resolve food names from the first nonempty uncountable, localized or number
title, using the language fallback within each candidate; literal food-name
characters remain unchanged.
Existing Markdown files, including manual notes, are never overwritten:
repeated exports create new files. If a title is taken,
the recipe id and then a counter are appended (Title-<recipe id>.md,
Title-<recipe id>-2.md). Complete notes are published without replacing files, so concurrent exports
retain distinct names. Command output lists the actual paths.
The Paprika and Tandoor exports write their files into the current directory
and never overwrite an existing file. If the preferred name (the asciified
recipe title, or allrecipes.paprikarecipes for a Paprika export of several
recipes) is taken, for example by an earlier export or by a second recipe with
the same title, the recipe id and then a counter are appended
(Title-<recipe id>.zip, Title-<recipe id>-2.zip, allrecipes-2.paprikarecipes).
The command output lists the names that were actually written.
Title-derived names are limited to 240 UTF-8 bytes, including extension and any
recipe ID/counter suffix. The display title stem is shortened on character
boundaries after transliteration, when applicable; suffixes remain intact and
collision attempts retain that byte limit. Long or localized titles stay complete
inside the recipe JSON and Markdown’s quoted title front matter.
Each publication tries at most 16 sequential names, then four names with a random
16-hex identity suffix (20 link attempts total). If all collide, export stops with
an error asking you to move existing exports or choose another location. Existing
files remain unchanged; publication and directory-sync rules also cover fallback
names.
Archives, Markdown notes and their images are fully copied and flushed in sibling
staging before atomic no-clobber publication. An incomplete copy stops before
any final name is linked for that file, and existing files remain unchanged.
The copy verifies the opened regular file’s size and generation through EOF.
After publication, source cleanup checks that the original path still names
the copied generation, preserving a replacement or a modified source.
ZIP archive creation checks every container write, including library exports
without a batch budget. Paprika’s budgeted export also checks writes of its
gzip-compressed members. An incomplete write aborts before archive publication.
Markdown checks the initial staged byte count of each image and note before
publishing it. If a note write is incomplete,
the exporter attempts to remove that recipe’s published image and reports
the failed recipe while preserving earlier exports. The exporter publishes
each Markdown asset and syncs its directory before publishing the note that
references it. Directory entries
for newly created Markdown export/assets directories are synced before use;
each final export directory is synced after its file is linked. Unsupported
directory-sync operations retain the portability fallback; real I/O errors are
reported. Sibling staging, linking and cleanup use one open destination
directory, and sync uses that same descriptor. This publication path requires
directory-relative file operations. The destination filesystem must support
hard links (FAT/exFAT and some network mounts do not); otherwise export stops
with an error naming the directory and publishes no partial final file.
If a link reports an error after installing the export’s staging inode at the
final name, the export verifies the link and proceeds with directory sync.
When the final name cannot be inspected, the export reports that publication
could not be confirmed and retains any assets the note may reference.
If the destination path moves or refers to a replacement directory after
linking, the export reports the movement and the linked filename in the
original directory. The replacement directory is left alone. Batch receipts
list the requested path under uncertain_paths so it can be checked before
retrying.
Failures before note publication remove attempt-owned assets when safe and sync
the asset directory after removal. If either operation raises an I/O error,
the export attempts to log uncertain asset cleanup and reports the original note
failure even if logging raises. Warnings about a failed staging unlink are also
best-effort and preserve the publication result. Paprika, Tandoor and
Markdown also warn if a temporary staging directory cannot be removed. A
confirmed archive or Markdown note and its image still count as completed.
If staging failed earlier, the original export error reaches the caller.
A failure or interruption during post-link directory sync reports the published
path with uncertain durability, retaining all visible files and assets a
visible note references.
Tandoor and Markdown stop at the first failed recipe. Their CLI errors list
completed exports and Markdown assets, the failing recipe ID, and the count of
untouched recipes. The error separately lists current paths with uncertain
publication or durability and retained assets. Earlier completed exports are
never removed.
Library callers receive BatchExportError with completed_paths,
completed_assets, failed_recipe_id, remaining_count, uncertain_paths and
retained_assets; successful return types are unchanged. Counts exclude the
failing recipe. These receipts are bounded by the 4,096-recipe batch admission.
Inspect those files before retrying; a retry uses a free filename. Forced
termination may leave hidden .kptncook-* staging or complete unreferenced assets.
Final names contain complete files; power-loss durability depends on filesystem
support for file/directory sync.
Paprika serializes and compresses one recipe at a time, so cover/JSON memory
does not grow with the number of exported recipes. Its small single-recipe and
bulk serialization helpers remain available to library callers; the bulk helper
still materializes its results when called directly.
Each export() batch has a cumulative 100 MiB asset allowance and a 256 MiB
output-work allowance, in addition to the 10 MiB per-image limit and 4,096-recipe
count ceiling. Markdown inspects at most 4,097 recipes from an iterable and
refuses an oversized batch before creating export directories or downloading
images. If Content-Length exceeds the remaining batch asset allowance,
the download stops before reading the body. Downloads charge each received
chunk before retaining it, including
chunks from failed or oversized optional images. The downloader may receive one
extra chunk to detect overflow. Exhausting the allowance stops the batch.
ZIP members read from disk are charged for each chunk before compression,
including bytes added after the source’s initial stat. Output also charges other
data fed into compression, actual gzip/ZIP writes, staged Markdown notes/assets
and sibling publication copies before each write. Header rewrites count again;
hard links add no data bytes. These are cumulative work ceilings, not final
archive-size estimates; temporary copies consume allowance even when later
deleted. Allowances reset for each export call.
A limit error preserves earlier completed Tandoor/Markdown files and reports the
same partial-batch receipts above. Paprika publishes one archive for the whole
batch: staged recipes are not completed exports, and a limit refusal before its
final link leaves all recipes unpublished. BatchExportError.unpublished_count
reports recipes without a completed export (including any uncertain current
publication), separately from the untouched count; final Paprika assembly errors
use archive as the failing identity. Split large batches into smaller selections
and inspect receipts before retrying. Direct rendering/serialization helpers do
not constitute a file-export batch; their existing return types are unchanged.
The library PaprikaExporter.save_recipes helper builds its archive from exactly
the requested IDs, including an empty archive for an empty request. Reusing its
work directory never includes stale or unrelated .paprikarecipe files; those
unrequested files are left untouched.
The helper stages all gzip sidecars and the ZIP before changing any destination
files. A failure while preparing a sidecar or the ZIP preserves the previous
archive and sidecars. Once ready, it replaces the requested sidecars one at a
time and then replaces the archive. A replacement failure may leave some
complete sidecars visible with the previous archive. A directory sync failure
after archive replacement reports uncertain durability and retains visible files.
Paprika preserves quotes, backslashes, whitespace and Unicode in recipe text.
All three local exporters preflight every recipe ID before writing any output:
IDs must be portable single filename components of at most 128 bytes (no slash,
backslash, NUL, dot segments, reserved names or overlong components). Valid opaque
IDs remain unchanged in recipe content; IDs do not need to be 24-digit OIDs.
An unsafe ID refuses the batch before downloads or file creation. This check
covers ID components; other filesystem failures remain subject to the existing
export error behavior.
Absent or ambiguous Paprika covers are optional, like failed downloads: every
recipe’s text remains in the archive with empty photo fields.
Its temporary archive files are removed on success and failure; only the final
export persists. Export errors are reported instead of silently omitting recipes.
HTTP diagnostics
HTTP failures display the status and caller-supplied action, or a fixed transport
category (timeout, connection, network, protocol or HTTP error). Raw exceptions,
request URLs and arbitrary response messages are omitted, so echoed API keys,
bearer tokens and signed URLs cannot enter diagnostics. Only a small allowlist
of known protocol details is displayed as plain text (for example
missing_kptnkey and recipe uniqueness messages). JSON details must fit in
16 KiB and use application/json or an application/*+json media type,
case-insensitively. Malformed, unexpected and oversized bodies are ignored.
CLI error boundaries escape Rich markup before rendering.
Repository warnings
Incoming recipes are validated before any repository write.
Store reads accept regular files only (symlinks are refused) and are limited to
64 MiB of UTF-8 JSON, including files that grow while being read. Invalid encoding,
nonregular files and oversized stores stop reads and mutations without replacing
the primary or recovery snapshot. A missing store remains an empty repository.
Before parsing JSON, the reader verifies that the byte count matches the size of
the opened file. An incomplete read stops listings and mutations. A complete
read can still use the opened snapshot if a writer atomically replaces the file.
Integers that exceed Python’s decimal digit limit are reported as invalid JSON
without exposing the value or replacing either snapshot.
Duplicate JSON object member names at every nesting level (including escaped
spellings) are refused before model validation, with no member names or values
in the diagnostic. Repeated array values are unaffected. The repository refuses
nonfinite numbers, including overflow to infinity, anywhere in a stored recipe
or before serializing a write. It also refuses unpaired Unicode surrogates in
recipe keys and string values. Paired JSON escapes and literal supplementary
characters are accepted. Errors identify the record position without quoting
its data. Refused reads prevent exports, and refused writes preserve the
primary and recovery backup.
Library deletion calls deduplicate requested IDs in encounter order, reporting
each deleted or missing ID once and committing at most once.
Identifier-based reads and mutations reject records whose _id.$oid is not a
nonempty string. The error identifies the record position without exposing its
payload; mutations leave the repository and recovery backup unchanged. Repair
the malformed record manually before retrying.
Repeated OIDs within a stored snapshot or an incoming batch are refused, even
when their payloads are identical. The bounded error identifies both positions;
mutations leave main and backup bytes unchanged. Errors distinguish incoming feed
batches from stored snapshots; a repeated daily/today feed is refused in full,
including exact copies. Check the feed and retry rather than editing the local
repository for an incoming-batch error. A single incoming record may
still replace its existing unique identity. Network-to-store commands (today,
favorites, ID lookup and browsing with --save) capture local records before
fetching. Under the writer lock, the complete saved record for each incoming ID
must still match that baseline (including absence). A concurrent insertion,
edit or deletion of one of those IDs refuses the entire fetched batch with a
refresh conflict before backup/publication. Fetch again to retry. Changes to
unrelated IDs are retained and do not conflict; network requests never hold the
writer lock. No remote response revision ordering is assumed. Direct library
add/add_list calls remain explicit replacements; pass expected= to
add_list or save_recipe_entries to bind a fetch to list_by_id() results.
After the conflict check, a batch whose complete records already serialize
identically to the stored records leaves the primary file and previous recovery
backup intact. Save counts
include all accepted input recipes, including those already saved.
Repository mutations use the existing portable portalocker backend on supported
POSIX and Windows systems. Every mutation must acquire the stable sibling
kptncook.json.lock before rereading and replacing data; lock failures refuse the
write with a repository error. Competing writers wait at most 30 seconds using
a monotonic deadline, then report a busy repository without modifying data or
backup. Retry after the current writer finishes. Use a local filesystem with working advisory locks,
and retain lock files while writers may run. Lock admission opens without following
symlinks or waiting on special files, requires a regular descriptor, and verifies
that its inode still owns the stable name after acquiring the lock. The writer
rechecks the lock identity immediately before replacing the recovery backup and
again before replacing the primary. A lock change detected before backup
publication preserves both snapshots. If detected after backup publication,
the refreshed backup remains and the primary stays unchanged. The application
retains the lock file after use. If opening the lock stream fails, the writer
closes the descriptor and reports a repository lock error before touching either snapshot.
Read-only recipe/export access remains available when locking fails.
Repository-backed commands now warn if kptncook.json contains stored entries
that can no longer be parsed into full recipes. The command continues with the
valid recipes instead of silently dropping the bad entries. If you need to
recover, inspect ~/.kptncook/kptncook.json and the previous snapshot in
~/.kptncook/kptncook.json.backup.
Writes serialize complete UTF-8 staging within the same 64 MiB limit as reads
before touching the primary or recovery backup. Over-capacity additions fail
without changing either snapshot; export and remove unneeded recipes, then retry
the smaller batch. An incomplete write to the staging file stops the mutation
before either snapshot is replaced. Every successful write remains reloadable.
Before replacing the repository, the exact bounded bytes admitted for the mutation
are copied to a sibling temporary backup, flushed and fsynced, then atomically
moved over .backup. An incomplete backup staging write aborts the operation
and preserves both existing files. The primary generation (device, inode, type, size and
modification/change timestamps) is checked after reading, before backup publication
and before primary replacement. A changed, removed or newly appeared primary
refuses the mutation; reload and retry after external editing has finished.
Read-only access (listing, exports, sync checks) does not take that pathname
check: a reader returns the complete generation it opened, even when a writer
atomically replaces the file meanwhile.
Backup copying never reopens an unchecked pathname or follows a substituted symlink
or FIFO. Direct library create_backup() calls use the same bounded regular-file
admission and acquire the same writer lock, with the same 30-second wait
budget. A direct backup holds the lock from snapshot selection through
publication and directory sync. External editors must avoid replacing files
during publication.
Backup and primary publication sync their containing directory where the OS
supports it. Genuine directory open and sync errors stop the write. If closing
the read-only sync descriptor fails, the tool attempts a short cleanup warning
and preserves the sync outcome for exports, configuration and recipe storage.
Before the first primary file is published, the store also syncs the resolved
parent chain, including directories left visible by a failed attempt.
Pre-existing ancestors the user cannot open for reading (such as a mode 0711
home directory) are skipped. An ancestor sync failure leaves the first primary
unpublished. Failure before backup
replacement leaves both snapshots intact. Failure syncing an already replaced
backup leaves the primary unchanged
and reports uncertain backup durability. Failure syncing an already replaced
primary reports that the new primary is published with uncertain durability;
it is never rolled back or deleted. Inspect/reload the visible primary and
backup before retrying; do not blindly restore the backup. Before renaming a
staging file, the writer verifies that its name still points to the file it
opened and synced. It also checks the primary stage before publishing the backup.
On failure, cleanup removes the writer’s own staging files and preserves any
replacement at a staging name. A later primary-write failure retains the
completed backup.
Delete recipes
Use indices from kptncook list-recipes or pass one or more --oid values.
Previews deduplicate IDs with linear membership work, retaining first-occurrence
order across indexes followed by explicit OIDs. Repeated IDs do not change
missing-ID or invalid-index reporting.
$ kptncook delete-recipes 0 2
$ kptncook delete-recipes --oid 635a68635100007500061cd7 --oid 635a68635100007500061cd8
$ kptncook delete-recipes 0 --force
The preview and selected store records come from one snapshot. After confirmation,
the writer lock protects a comparison of each still-present selected record with
that snapshot, including stored metadata. If any changed, the entire deletion is
refused with a reload message; no selected recipes are deleted. Reload and select
again before retrying. Unrelated recipe changes do not block deletion. Selected
IDs already removed by another writer are reported as missing; remaining unchanged
selections can still be deleted. --force skips the prompt and retains the same
snapshot comparison. Library callers can pass the preview’s RecipeInDb records
as expected={oid: record} to delete_by_ids; omitting expected keeps the
unconditional, idempotent ID-based API.
Dailies
Filter dailies by API fields such as recipeFilter (for example veggie) and
zone (timezone offset like +02:00). Add --save to store the daily recipes
in the local repository.
Dailies accepts a recipe list directly or under recipes, dailies or
items. Empty lists are valid. Unsupported envelopes or any non-object
list entries cause the entire response to fail before recipes are saved.
Recipe API requests that use language, store and preference defaults read all
missing values from a single settings snapshot. Library calls that supply all
three explicitly skip the settings lookup for those query parameters.
By default, no subscription status is sent. --not-subscribed sends
isSubscribed=false, as the free KptnCook app does; in a comparison on
2026-10-27 this changed only the retailer data in the response, which no
exporter uses. There is no option to claim a subscription.
$ kptncook dailies
$ kptncook dailies --zone +02:00 --recipe-filter veggie --save
$ kptncook dailies --not-subscribed --save
Discovery
Use discovery-screen to list discovery list ids and types. discovery-list
requires --list-type (latest, recommended, curated, automated).
List types are case-insensitive; short flags are -t for --list-type and
-i for --list-id. For curated and automated, pass the list id from
discovery-screen with --list-id. For latest and recommended, omit
--list-id.
The CLI and public client accept only these four list types. List IDs are single
opaque path components containing Unicode letters/numbers or -._~; . and ..,
percent escapes, separators, controls and query/fragment markers are refused
before authenticated requests. Unicode IDs are percent-encoded in the route.
Outer spaces are trimmed, as in the CLI’s other list input normalization.
Recipe identifiers retain the supported identifier, uid, _id/$oid,
id, recipeId/recipe_id and recipe/summary wrapper shapes, up to 16 dictionary
levels. Explicit identifier and uid values and typed ID pairs continue to
accept nonblank opaque strings. Values without a usable string or supported
wrapper are skipped so later aliases can resolve. If no usable ID remains,
no recipe search is sent. Cycles or deeper wrappers stop resolution with a
payload-free error.
Favorites backup rejects the whole identifier batch before recipe search or
storage, including when another favorite is valid; no partial backup is saved.
Use --no-quick-search if you only want discovery list ids, and add --save
to discovery-list to store the resolved recipes locally.
Discovery screen entries are printed as id | title | type so you can copy the
list id into discovery-list. The screen uses the first non-null ID from id,
_id, listId, list_id and oid, in that order. Discovery list entries are
recipe summaries, which the CLI resolves to full recipes before printing or saving.
If discovery-screen receives unreadable JSON, including duplicate object
members, it exits with status 1 and a short error without rendering any entries.
$ kptncook discovery-screen
$ kptncook discovery-screen --no-quick-search
$ kptncook discovery-list --list-type recommended
$ kptncook discovery-list --list-type latest
# list ids for curated/automated lists come from discovery-screen output
$ kptncook discovery-list -t curated -i 12345 --save
$ kptncook discovery-list --list-type automated --list-id 67890
Ingredients
Ingredient discovery and ingredient-based recipes require
KPTNCOOK_ACCESS_TOKEN. Ingredient ids can be repeated or comma-separated. Copy
the ID from kptncook ingredients-popular, which prints id | name and selects
the first non-null ID from _id, id, ingredientId, ingredient_id and oid,
in that order. Use kptncook kptncook-access-token to generate a token.
Popular ingredient replies may be a list of objects or contain such a list
under ingredients, items or data. The first list in that order is used.
An empty list reports “No popular ingredients found.” Unreadable JSON, a
missing list or a non-object list entry makes the command exit with status 1
and the standard unreadable-response error before printing any entries.
The --ingredient-id flag is required and repeatable for
recipes-with-ingredients (-i is the short flag).
Add --save to recipes-with-ingredients to store matched recipes locally.
Recipes are resolved to full recipe payloads before printing or saving.
$ kptncook ingredients-popular
$ kptncook recipes-with-ingredients -i 123 -i 456 --save
$ kptncook recipes-with-ingredients --ingredient-id 123,456
Onboarding recipes
The --tag flag is required and repeatable; tags accept repeated values or
comma-separated lists. Tags are KptnCook tag slugs (for example
rt:diet_vegetarian). Recipes are resolved to full recipe payloads before
printing or saving.
$ kptncook onboarding --tag rt:diet_vegetarian
$ kptncook onboarding --tag "low-carb,high-protein" --save
Environment
First, create the configuration directory and .env file:
$ mkdir -p ~/.kptncook
$ touch ~/.kptncook/.env
Alternatively, you can run the setup helper to create the .env file, prefill the
default API key, and optionally fetch an access token. It is available both as a
kptncook subcommand and as a standalone command:
$ kptncook setup
# or, equivalently:
$ kptncook-setup
The .env is written to $KPTNCOOK_HOME/.env when KPTNCOOK_HOME is set,
otherwise to ~/.kptncook/.env. Guided setup owns and closes its authentication
client on success and every failure, before attempting to save the token. Only a
complete successful response containing an admitted access token is saved.
After scaffolding, setup initializes a missing or blank API key under the
configuration write lock. If another setup has already filled it in, setup
keeps that key and reports that it is already set.
Setup saves --username-command and --password-command together in one
configuration update. Either option can be used on its own. When fetching a
token, setup runs explicit commands as supplied and reads any omitted command
from the configuration snapshot it just saved.
Setup reads the configured API key immediately before login and checks it again
under the configuration write lock. If the key changed during login, setup
preserves the current configuration and reports that setup should be rerun.
KptnCook and Mealie tokens must contain 1–8,192 visible ASCII characters
(! through ~); whitespace, controls, non-ASCII text and oversized tokens
are refused before persistence or changes to authenticated client state.
Valid opaque tokens are kept unchanged. The optional blank
KPTNCOOK_ACCESS_TOKEN= in the starter configuration means no token.
HTTP, transport and malformed-response failures preserve an existing token and
report a bounded diagnostic without response payloads.
Configuration is validated lazily. If you run a command before configuring the
API key, kptncook will scaffold the .env file when that command first needs
settings and then exit; just re-run the command after updating the file. help
and other non-config commands do not force .env validation up front.
Invalid settings produce at most 16 field diagnostics with safe error codes and
format guidance; rejected values, URLs and validator context are never printed.
Correct the named setting in your shell or .env and re-run the command.
Direct Settings validation also hides inputs in normal exception formatting;
Pydantic’s programmatic errors() data remains sensitive and should not be logged.
Runtime settings read .env only from a regular UTF-8 file of at most 64 KiB,
the same admission rule used by setup. An unreadable, oversized, invalid UTF-8
or special file stops runtime configuration with a short error before client
setup. A short read or a detected in-place change is refused before parsing.
When an atomic replacement leaves the already-open file intact, the reader
can still use that complete snapshot. Missing files are treated as empty.
For library callers, Settings(_env_file=path) selects a different file and
_env_file=None disables dotenv. Constructor values take precedence over shell
variables, which take precedence over dotenv values.
Library callers can use clear_settings_cache() to reload settings on the next
access through get_settings(). An in-flight load reuses settings already
cached by another caller, even if its own load raised SettingsError. After a
cache clear, an in-flight load retries if the cache is still empty. A
SettingsError from the current generation reaches the caller when the cache
is empty. Overrides on the lazy settings proxy carry over to the current
cached instance.
Then set environment variables in the ~/.kptncook/.env file (or directly in your shell). You’ll need to set at least the KPTNCOOK_API_KEY variable. If you want to sync the recipes with mealie, set MEALIE_API_TOKEN or MEALIE_USERNAME/MEALIE_PASSWORD.
When kptncook creates or updates ~/.kptncook/.env, it applies owner-only read/write permissions (0600) where the platform supports it, because the file may contain access tokens, passwords, or trusted shell commands. Updates are written to an owner-only temporary file next to .env, synced and then moved into place. Failures before replacement leave the previous file intact.
An incomplete write of the initial UTF-8 text stops the operation before any
settings are applied to the temporary file.
The containing directory is synced after replacement. Unsupported directory sync
uses the shared portability fallback; real disk errors (such as I/O failure or
full storage) exit with a value-free “Configuration was published; durability is
uncertain” diagnostic, including during first-run scaffolding. The complete new
private file stays visible; it is never rolled back or deleted. Keep that file,
check storage health and verify the configuration locally before retrying setup
or refreshing a token. Library callers receive ConfigurationPublishedError
(an OSError); scaffold calls also raise it rather than returning False.
Cooperating setup/token writers hold an OS file lock across rereading and atomic
publication, so concurrent updates preserve other keys. Paths are resolved before
locking, including symlink targets. The stable sibling .<filename>.lock (for
.env, ..env.lock) is retained after use; do not delete it while writers may
be running. Manual editors must coordinate separately. Setup and runtime use python-dotenv
syntax, including single/double quotes, export, spaced assignments and inline
comments. Updates quote literal values (including backslashes, quotes, spaces,
# and newlines) and preserve unrelated lines. Normal python-dotenv ${VAR}
interpolation still applies when reading configuration. Scaffolding uses the same
lock and does not overwrite an
README 内容过长,已截取前 64 KB。完整内容请前往 GitHub 仓库查看。
评论