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_ACCEPT_VERSION

Ghost API version the client is written against, sent as the Accept-Version header on every request

BLOG_URL

Public blog base URL; posts live at {BLOG_URL}/{slug}.

ADMIN_TOKEN_LIFETIME

Admin API JWT lifetime; Ghost allows at most five minutes

ADMIN_API_KEY_HELP

How to get a key that can create draft posts

Functions

check_ghost_admin_api_key(admin_api_key)

Check that a key can authenticate to the Ghost Admin API.

create_ghost_admin_token(admin_api_key[, now])

Create a short-lived Admin API JWT token.

fingerprint_post_text(post_html)

Fingerprint the visible text of a post body.

strip_ghost_ref(url)

Remove the ref tracking parameter Ghost adds to links.

Classes

DraftRecord

What the pipeline last wrote to a draft, to tell whether an editor has changed it since.

GhostAdminClient

Upload images and manage draft posts with the Ghost Admin API.

GhostContentClient

Read published posts with the Ghost Content API.

GhostPost

Subset of Ghost post fields we use.

Exceptions

GhostAPIError

Ghost API returned an error response.

GHOST_ACCEPT_VERSION = 'v5.0'

Ghost API version the client is written against, sent as the Accept-Version header on every request

BLOG_URL = 'https://tradingstrategy.ai/blog'

Public blog base URL; posts live at {BLOG_URL}/{slug}. The Ghost API returns ghost.io URLs; 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.io site name into the new post.

strip_ghost_ref(url)

Remove the ref tracking parameter Ghost adds to links.

Parameters

url (str) – Link from Ghost post HTML, e.g. https://youtu.be/abc?ref=example.ghost.io.

Returns

The link without the parameter, e.g. https://youtu.be/abc.

Return type

str

ADMIN_TOKEN_LIFETIME = datetime.timedelta(seconds=300)

Admin API JWT lifetime; Ghost allows at most five minutes

exception GhostAPIError

Bases: Exception

Ghost 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 kid header 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 GhostAdminClient creates 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

str

class GhostPost

Bases: object

Subset 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.

id: str

Ghost object id

title: str

Post title

slug: str

URL slug

status: str

draft, scheduled or published

html: Optional[str]

Post body, when requested with formats=html

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 DraftRecord compares it by string equality

custom_excerpt: Optional[str]

Post excerpt

feature_image: Optional[str]

Feature image URL

static from_api(data)

Parse a post from a Ghost API response.

Parameters

data (dict) – One entry of the posts list.

Returns

Parsed post.

Return type

eth_defi.vault_report.ghost.GhostPost

__init__(id, title, slug, status, html, published_at, updated_at, custom_excerpt=None, feature_image=None)
Parameters
Return type

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=true would refuse every regeneration and leave only force, 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.

Parameters

post_html (str) – Post body HTML.

Returns

SHA-256 hex digest of the normalised text.

Return type

str

class DraftRecord

Bases: object

What 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().

post_id: str

Ghost post id

updated_at: Optional[str]

updated_at returned by Ghost for the pipeline’s write

fingerprint: str

fingerprint_post_text() of the body the pipeline sent

title: str

Title the pipeline set

custom_excerpt: Optional[str]

Excerpt the pipeline set

feature_image: Optional[str]

Feature image after the write; the pipeline never sets one

matches(post)

Check that a draft is as the pipeline left it.

A later updated_at alone 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

True when nobody has changed the draft’s text or settings.

Return type

bool

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 None if the file does not exist.

Return type

Optional[eth_defi.vault_report.ghost.DraftRecord]

__init__(post_id, updated_at, fingerprint, title, custom_excerpt, feature_image)
Parameters
Return type

None

class GhostContentClient

Bases: object

Read 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)
Parameters
  • api_url (str) – Ghost site API URL, e.g. https://example.ghost.io.

  • content_api_key (str) – Content API key.

  • timeout (float) – HTTP timeout in seconds.

Return type

None

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

Optional[eth_defi.vault_report.ghost.GhostPost]

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
  • nql_filter (str) – NQL filter, e.g. title:~'episode' for titles containing a word.

  • limit (int) – Maximum number of posts.

Returns

Posts including their HTML bodies, newest first.

Return type

list[eth_defi.vault_report.ghost.GhostPost]

class GhostAdminClient

Bases: object

Upload 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, see check_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, see check_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 returned storage.ghost.io URLs, 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

str

fetch_post_by_slug(slug)

Fetch a post in any status by its slug.

Parameters

slug (str) – Post slug.

Returns

The post, or None if it does not exist.

Return type

Optional[eth_defi.vault_report.ghost.GhostPost]

delete_post(post_id)

Delete a post.

Parameters

post_id (str) – Ghost post id.

Return type

None

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 when last_write shows nobody has edited it since the pipeline wrote it, see DraftRecord.matches(). force skips 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 None if 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

Optional[eth_defi.vault_report.ghost.GhostPost]

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=html and 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.

  • custom_excerpt (Optional[str]) – Post excerpt.

  • tags (Optional[list[str]]) – Tag names.

  • 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

eth_defi.vault_report.ghost.GhostPost

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

str