vault_report.ghost
Documentation for eth_defi.vault_report.ghost Python module.
Minimal Ghost blog API client for the vault report.
The Content API is read-only and uses a content API key. We use it to find the previous report post and the latest podcast episodes, see
eth_defi.vault_report.podcasts.The Admin API is needed to upload images and create draft posts. It uses an
{id}:{secret}admin API key, created in Ghost Admin under Settings → Integrations → Add custom integration, and short-lived JWT tokens signed with the secret, see token authentication.
The client is a thin requests wrapper over the few endpoints the report
needs; the request parameters that matter for safety (status: draft,
source=html, updated_at) are all in this file.
The Admin API client is deliberately unable to publish: every write sends
status: draft. On top of that, GhostAdminClient.fetch_writable_draft()
guards the editor’s work. It never touches a published or scheduled post,
and replaces an existing draft only when a DraftRecord of the
pipeline’s last write shows nobody has edited it since. Because Ghost
rewrites the HTML it is given, that comparison uses a text fingerprint,
fingerprint_post_text(), rather than the raw HTML. See the Ghost
post draft section of README-best-vaults-news.md for the operator’s view
of these rules.
API keys are secrets: no error message or log line includes a key or a URL that carries one.
Module Attributes
Ghost API version the client is written against, sent as the |
|
Public blog base URL; posts live at |
|
Admin API JWT lifetime; Ghost allows at most five minutes |
|
How to get a key that can create draft posts |
Functions
|
Check that a key can authenticate to the Ghost Admin API. |
|
Create a short-lived Admin API JWT token. |
|
Fingerprint the visible text of a post body. |
|
Remove the |
Classes
What the pipeline last wrote to a draft, to tell whether an editor has changed it since. |
|
Upload images and manage draft posts with the Ghost Admin API. |
|
Read published posts with the Ghost Content API. |
|
Subset of Ghost post fields we use. |
Exceptions
Ghost API returned an error response. |
- GHOST_ACCEPT_VERSION = 'v5.0'
Ghost API version the client is written against, sent as the
Accept-Versionheader on every request
- BLOG_URL = 'https://tradingstrategy.ai/blog'
Public blog base URL; posts live at
{BLOG_URL}/{slug}. The Ghost API returnsghost.ioURLs; readers use this domain.
- GHOST_REF_PARAMETER = re.compile('([?&])ref=[a-z0-9.-]+\\.ghost\\.io(&?)')
Ghost adds this tracking parameter to outbound links in its HTML output. HTML and links copied from earlier posts (evergreen sections, podcast links) would otherwise carry the internal
ghost.iosite name into the new post.
- strip_ghost_ref(url)
Remove the
reftracking parameter Ghost adds to links.
- ADMIN_TOKEN_LIFETIME = datetime.timedelta(seconds=300)
Admin API JWT lifetime; Ghost allows at most five minutes
- exception GhostAPIError
Bases:
ExceptionGhost API returned an error response.
- __init__(*args, **kwargs)
- __new__(**kwargs)
- add_note(note, /)
Add a note to the exception
- with_traceback(tb, /)
Set self.__traceback__ to tb and return self.
- ADMIN_API_KEY_FORMAT = re.compile('^[0-9a-f]{24}:[0-9a-f]{64}$')
Admin API key or staff access token: a 24-character hex id and a 64-character hex secret
- CONTENT_API_KEY_FORMAT = re.compile('^[0-9a-f]{26}$')
Content API key: 26 hex characters, read-only
- ADMIN_API_KEY_HELP = 'Creating a draft post needs the Ghost Admin API. In Ghost Admin, open Settings -> Integrations -> Add custom integration and copy its Admin API key, or copy the Staff access token from your staff user profile. Put it in your secrets file, outside the repository, as GHOST_ADMIN_API_KEY.'
How to get a key that can create draft posts
- check_ghost_admin_api_key(admin_api_key)
Check that a key can authenticate to the Ghost Admin API.
The Content API is read-only, so its key cannot create posts, drafts included. The Admin API takes an integration’s Admin API key or a staff access token, both
{id}:{secret}. The key itself is never included in the error.- Parameters
admin_api_key (str) – Key to check.
- Raises
GhostAPIError – The key is a Content API key or not in
{id}:{secret}format.- Return type
None
- create_ghost_admin_token(admin_api_key, now=None)
Create a short-lived Admin API JWT token.
Implements Ghost token authentication: HS256 signature with the hex-decoded secret, the key id in the
kidheader and/admin/audience. A JWT with one fixed algorithm is a few lines of standard library code, so the client needs no JWT dependency.Ghost rejects tokens that live longer than five minutes, so
GhostAdminClientcreates a fresh token for every request rather than tracking expiry across a run that may span the investability check and the image uploads.- Parameters
admin_api_key (str) – Admin API key in
{id}:{secret}format.now (Optional[datetime.datetime]) – Token issue time, naive UTC. Defaults to the current time.
- Returns
Encoded JWT.
- Return type
- class GhostPost
Bases:
objectSubset of Ghost post fields we use.
Parsed from both the Content API and the Admin API, which return the same post object shape; see the Admin API posts reference.
- published_at: Optional[datetime.datetime]
Publication time, naive UTC
- updated_at: Optional[str]
Last update timestamp as returned by Ghost, kept as the raw string: Ghost requires it back unchanged on an update to detect a concurrent edit, and
DraftRecordcompares it by string equality
- static from_api(data)
Parse a post from a Ghost API response.
- Parameters
data (dict) – One entry of the
postslist.- Returns
Parsed post.
- Return type
- __init__(id, title, slug, status, html, published_at, updated_at, custom_excerpt=None, feature_image=None)
- fingerprint_post_text(post_html)
Fingerprint the visible text of a post body.
Ghost converts the HTML the pipeline sends into its editor format and back, and re-saves a draft when it is opened in the editor, so the HTML itself changes without an edit. The fingerprint covers only the text: images are dropped, HTML cards such as tables count as one placeholder, and whitespace is normalised. The HTML the pipeline sent and the HTML Ghost returns for an unedited draft have the same fingerprint.
The trade-off is deliberate: the fingerprint must never flag Ghost’s own rewriting as an edit, or
GHOST_OVERWRITE_DRAFT=truewould refuse every regeneration and leave onlyforce, which protects nothing. As a consequence it does not see changes inside raw HTML cards (the tables, the podcast list), swapped images or changed link targets; it does see every change to the text of headings, paragraphs, lists and links, which is where the editor writes. Block boundaries are kept as line breaks, so moving text between paragraphs changes the fingerprint too.
- class DraftRecord
Bases:
objectWhat the pipeline last wrote to a draft, to tell whether an editor has changed it since.
Stored as JSON next to the download cache after every write, see
GhostAdminClient.fetch_writable_draft().- fingerprint: str
fingerprint_post_text()of the body the pipeline sent
- matches(post)
Check that a draft is as the pipeline left it.
A later
updated_atalone is not an edit, because Ghost re-saves a draft when it is opened, so the text and settings are compared too.- Parameters
post (eth_defi.vault_report.ghost.GhostPost) – The draft, fetched with
formats=html.- Returns
Truewhen nobody has changed the draft’s text or settings.- Return type
- save(path)
Write the record as JSON.
- Parameters
path (pathlib.Path) – Record file.
- Return type
None
- classmethod load(path)
Read a record written by
save().- Parameters
path (pathlib.Path) – Record file.
- Returns
The record, or
Noneif the file does not exist.- Return type
- class GhostContentClient
Bases:
objectRead published posts with the Ghost Content API.
- Parameters
api_url – Ghost site API URL, e.g.
https://example.ghost.io.content_api_key – Content API key.
timeout – HTTP timeout in seconds.
- __init__(api_url, content_api_key, timeout=30.0)
- fetch_latest_post_by_slug_prefix(slug_prefix)
Find the most recently published post whose slug starts with a prefix.
Uses a NQL filter
slug:~^'prefix'.- Parameters
slug_prefix (str) – E.g.
the-best-performing-stablecoin-vaults.- Returns
The latest post including its HTML body, or
None.- Return type
- fetch_latest_posts(nql_filter, limit)
Fetch the most recently published posts that match a filter.
See the Content API filtering documentation for the NQL syntax.
- Parameters
- Returns
Posts including their HTML bodies, newest first.
- Return type
- class GhostAdminClient
Bases:
objectUpload images and manage draft posts with the Ghost Admin API.
Create an Admin API client after checking the key format.
The key is validated before any request, so a Content API key or a malformed key fails early without being sent or printed.
- Parameters
api_url – Ghost site API URL, e.g.
https://example.ghost.io.admin_api_key – Admin API key or staff access token in
{id}:{secret}format, seecheck_ghost_admin_api_key().timeout – HTTP timeout in seconds.
- Raises
GhostAPIError – The key cannot authenticate to the Admin API.
- __init__(api_url, admin_api_key, timeout=60.0)
Create an Admin API client after checking the key format.
The key is validated before any request, so a Content API key or a malformed key fails early without being sent or printed.
- Parameters
api_url (str) – Ghost site API URL, e.g.
https://example.ghost.io.admin_api_key (str) – Admin API key or staff access token in
{id}:{secret}format, seecheck_ghost_admin_api_key().timeout (float) – HTTP timeout in seconds.
- Raises
GhostAPIError – The key cannot authenticate to the Admin API.
- Return type
None
- upload_image(path)
Upload an image to the Ghost media library.
The report bundle references charts and podcast images by relative paths, which only work in the local preview. Before the draft is created,
publish_report_draft()uploads each image here and rebuilds the post with the returnedstorage.ghost.ioURLs, so the draft is self-contained in Ghost. See the Admin API images endpoint.Each run uploads new copies, because the media library has no de-duplication by content; replacing a draft therefore leaves the previous run’s images in the library.
- Parameters
path (pathlib.Path) – Local image file. Ghost resizes uploads, so it must be a real image: a hand-made 1×1 PNG is rejected with “Unable to manipulate image”.
- Returns
Public URL of the uploaded image.
- Return type
- fetch_post_by_slug(slug)
Fetch a post in any status by its slug.
- Parameters
slug (str) – Post slug.
- Returns
The post, or
Noneif it does not exist.- Return type
- fetch_writable_draft(slug, *, overwrite_draft=False, last_write=None, force=False, existing_slug=None)
Fetch the existing post for a slug and check a draft can be written there without losing work.
An existing draft is replaced only with
overwrite_draft, and only whenlast_writeshows nobody has edited it since the pipeline wrote it, seeDraftRecord.matches().forceskips that comparison.- Parameters
slug (str) – Post slug.
overwrite_draft (bool) – Allow replacing an existing draft.
last_write (Optional[eth_defi.vault_report.ghost.DraftRecord]) – What the pipeline last wrote to this draft.
force (bool) – Replace an existing draft without comparing it with
last_write.existing_slug (Optional[str]) – Explicit draft to update and rename, e.g. when moving a waiting September draft to October. Must exist; the new slug must be free.
- Returns
The existing draft to replace, or
Noneif the slug is free.- Raises
GhostAPIError – A post with the slug has been published or scheduled, or a draft exists and may have been edited.
- Return type
- create_or_update_draft(title, slug, html, custom_excerpt=None, tags=None, *, overwrite_draft=False, last_write=None, force=False, existing_slug=None)
Create a draft post, or replace the body of an existing draft with the same slug.
See
fetch_writable_draft()for when an existing post is replaced.The body is sent with
?source=htmland Ghost converts it to its editor format. Content wrapped in<!--kg-card-begin: html-->/<!--kg-card-end: html-->comments becomes a raw HTML card; the previous report posts store their tables the same way.- Parameters
title (str) – Post title.
slug (str) – Post URL slug.
html (str) – Post body.
overwrite_draft (bool) – Replace the body of an existing draft with the same slug.
last_write (Optional[eth_defi.vault_report.ghost.DraftRecord]) – What the pipeline last wrote to the draft, see
fetch_writable_draft().force (bool) – Replace an existing draft without comparing it with
last_write.existing_slug (Optional[str]) – Explicit existing draft slug to update in place while changing its slug to
slug. Preserves the post id and editor link.
- Returns
The created or updated draft.
- Return type
- get_editor_url(post)
Get the Ghost Admin editor link for a post.
- Parameters
post (eth_defi.vault_report.ghost.GhostPost) – Post.
- Returns
Editor URL.
- Return type