tempest_fastapi_sdk.share¶
Prévia de link compartilhado: a página Open Graph e a imagem do card.
share
¶
Link previews for shared items: the Open Graph page and its card image.
A link shared on WhatsApp, Telegram, Instagram or X becomes a preview
built from the Open Graph tags of the HTML the URL returns, fetched by a
crawler that runs no JavaScript. :func:make_share_router serves that
HTML per item, from a resolver the service writes, and — with a
:class:ShareCardRenderer — the 1200x630 PNG the preview shows.
from tempest_fastapi_sdk.share import (
ShareCardRenderer,
SharePreviewSchema,
make_share_router,
)
app.include_router(
make_share_router(
resolve_trip,
public_url="https://api.example.com",
fallback=SharePreviewSchema(
title="BusCar",
description="Caronas entre cidades",
redirect_url="https://app.example.com",
),
renderer=ShareCardRenderer(),
)
)
For the image someone posts rather than the preview a link gets,
:class:ShareFrameRenderer draws a frame — story or square — with a QR
code in the middle, and :func:render_qr draws the QR code alone, both
with the brand logo inside the code at a measured, capped size.
The page needs nothing beyond the base install; the renderers need the
[image] extra (pillow, segno) and a TrueType font on the machine
(fonts-dejavu-core on Debian/Ubuntu). Importing this module needs
neither: Pillow is imported when a renderer is built.
Re-exports use the PEP 484 from x import Y as Y explicit re-export
form combined with __all__ so every type-checker accepts
from tempest_fastapi_sdk.share import make_share_router without a
diagnostic.
DEFAULT_FONT_CANDIDATES
module-attribute
¶
DEFAULT_FONT_CANDIDATES: tuple[tuple[str, str], ...] = (
(
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
),
(
"/usr/share/fonts/dejavu-sans-fonts/DejaVuSans.ttf",
"/usr/share/fonts/dejavu-sans-fonts/DejaVuSans-Bold.ttf",
),
("/usr/share/fonts/TTF/DejaVuSans.ttf", "/usr/share/fonts/TTF/DejaVuSans-Bold.ttf"),
(
"/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
),
)
System font pairs (regular, bold) tried in order: Debian/Ubuntu
(fonts-dejavu-core), Fedora, Arch, then Liberation.
OG_IMAGE_HEIGHT
module-attribute
¶
Height Open Graph recommends for summary_large_image previews.
OG_IMAGE_WIDTH
module-attribute
¶
Width Open Graph recommends for summary_large_image previews.
LAYOUTS
module-attribute
¶
LAYOUTS: dict[ShareFrameLayoutEnum, _Layout] = {
ShareFrameLayoutEnum.STORY: _Layout(
width=1080,
height=1920,
margin=80,
header_y=120,
header_height=96,
photo_diameter=320,
photo_beside_title=False,
people_y=310,
title_size=64,
subtitle_size=40,
panel_size=780,
panel_y=880,
url_size=40,
caption_size=40,
),
ShareFrameLayoutEnum.SQUARE: _Layout(
width=1080,
height=1080,
margin=64,
header_y=48,
header_height=72,
photo_diameter=150,
photo_beside_title=True,
people_y=150,
title_size=52,
subtitle_size=34,
panel_size=600,
panel_y=330,
url_size=34,
caption_size=30,
),
}
Geometry of each layout, in pixels.
MAX_PHOTO_PIXELS
module-attribute
¶
Largest photo, in pixels, decoded before cropping.
DEFAULT_QR_LOGO_FRACTION
module-attribute
¶
Default side of the logo as a fraction of the QR side (6 % of the area).
MAX_QR_LOGO_FRACTION
module-attribute
¶
Largest fraction accepted; 0.40 already failed on a 30-character link.
PNG_MEDIA_TYPE
module-attribute
¶
Media type of the preview image.
ShareCardRenderer
¶
ShareCardRenderer(
*,
background: str | tuple[str, str] = ("#0b3d91", "#061f4a"),
text_color: str = "#ffffff",
muted_color: str = "#c7d4f0",
accent_color: str = "#ffd166",
chip_color: str = "#ffffff",
chip_text_color: str = "#0b3d91",
logo: bytes | Path | None = None,
font_path: Path | None = None,
bold_font_path: Path | None = None,
)
Bases: _BrandRenderer
Draws share cards as 1200x630 PNG.
Layout, top to bottom: brand (accent) with the logo at the right,
kicker (muted), title (bold, shrinks from 72 to 48 px on one
line, else wraps to two lines at 56 px, then is cut with …), the
lines (icon in the accent color + text), the chips and the
footer. Text never
leaves the margins: what does not fit shrinks, is cut, or — for
lines and chips — is dropped.
Construction arguments are those of the shared base: background,
text_color, muted_color, accent_color, chip_color,
chip_text_color, logo, font_path and bold_font_path.
Rendering is CPU-bound and synchronous; the share router calls
:meth:render through :func:asyncio.to_thread.
Attributes:
| Name | Type | Description |
|---|---|---|
width |
int
|
Image width, :data: |
height |
int
|
Image height, :data: |
render
¶
render(card: ShareCardSchema) -> bytes
Draw card as a PNG.
The output is a pure function of the card and the renderer's colors, fonts and logo — same inputs, same bytes in the same Pillow and FreeType versions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
card
|
ShareCardSchema
|
What to draw. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
The PNG, :data: |
ShareFrameRenderer
¶
ShareFrameRenderer(
*,
background: str | tuple[str, str] = ("#0b3d91", "#061f4a"),
text_color: str = "#ffffff",
muted_color: str = "#c7d4f0",
accent_color: str = "#ffd166",
chip_color: str = "#ffffff",
chip_text_color: str = "#0b3d91",
logo: bytes | Path | None = None,
font_path: Path | None = None,
bold_font_path: Path | None = None,
)
Bases: _BrandRenderer
Draws the shareable frame as PNG, in the story or square layout.
Top to bottom: logo and brand; the person's photo in a circle
ringed in the accent color (their initials when there is no photo),
title and subtitle; a white panel with the QR code of url
— the brand logo in its middle when the renderer has one; the link
written out; the caption. Text shrinks, then is cut with …;
nothing leaves the margins.
Construction arguments are the card's: background,
text_color, muted_color, accent_color, chip_color,
chip_text_color, logo, font_path and bold_font_path
(the chip colors are unused here). Fonts and colors fail at
construction, not at the first render.
Rendering is CPU-bound and synchronous; call it through
:func:asyncio.to_thread from a route.
render
¶
render(
frame: ShareFrameSchema,
*,
layout: ShareFrameLayoutEnum = STORY,
photo: bytes | None = None,
qr_logo_fraction: float = DEFAULT_QR_LOGO_FRACTION,
) -> bytes
Draw frame as a PNG.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
ShareFrameSchema
|
What to draw. |
required |
layout
|
ShareFrameLayoutEnum
|
Story (1080x1920) or square (1080x1080). |
STORY
|
photo
|
bytes | None
|
The person's photo; |
None
|
qr_logo_fraction
|
float
|
Side of the logo inside the QR code
over the QR side, at most
:data: |
DEFAULT_QR_LOGO_FRACTION
|
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
The PNG. |
Raises:
| Type | Description |
|---|---|
ImportError
|
Without the |
ValueError
|
When the photo does not decode, or
|
ShareResolver
¶
Bases: Protocol
Looks up the preview of one item.
Returns None when the item does not exist or must not be shown
(deleted, private, sold out): the router answers with the fallback
preview and no image. An exception propagates — a resolver failure
is a bug or an outage, not an unavailable item, and swallowing it
would hide both.
ShareCardLineSchema
¶
Bases: BaseSchema
One information line on the card.
Attributes:
| Name | Type | Description |
|---|---|---|
text |
str
|
The line's text, shrunk and then cut with |
icon |
str | None
|
A short glyph drawn before the text in the
accent color ( |
ShareCardSchema
¶
Bases: BaseSchema
Content of the 1200x630 preview image.
Attributes:
| Name | Type | Description |
|---|---|---|
title |
str
|
The headline. Shrinks, then wraps to two lines, then
is cut with |
brand |
str | None
|
Small text at the top left, in the accent color (the product name). |
kicker |
str | None
|
Muted line under the brand. |
lines |
list[ShareCardLineSchema]
|
Information lines under the title. Lines that do not fit above the chips are dropped. |
chips |
list[str]
|
Rounded labels near the bottom, left to right. Chips that would cross the right margin are dropped. |
footer |
str | None
|
Muted line at the bottom. |
Every text is collapsed to one line (line breaks and repeated spaces become one space); empty chips are dropped.
ShareFrameLayoutEnum
¶
Bases: BaseStrEnum
Shape of the shareable frame.
Attributes:
| Name | Type | Description |
|---|---|---|
STORY |
1080x1920, the status/story format. |
|
SQUARE |
1080x1080, for a chat or a group. |
ShareFrameSchema
¶
Bases: BaseSchema
Content of the shareable frame: a QR code with who and what around it.
Attributes:
| Name | Type | Description |
|---|---|---|
url |
str
|
Absolute |
title |
str
|
Main line under the photo — the person's name. |
subtitle |
str | None
|
Muted line under the title (the route). |
brand |
str | None
|
Product name next to the logo, in the accent color. |
caption |
str | None
|
Call to action under the link
( |
show_url |
bool
|
Write the URL under the QR code, without the scheme, for whoever cannot scan. |
Every text is collapsed to one line, as on the card.
SharePreviewSchema
¶
Bases: BaseSchema
What the share page says about one item.
Attributes:
| Name | Type | Description |
|---|---|---|
title |
str
|
|
description |
str
|
|
redirect_url |
str
|
Where a human lands — the app screen of the
item. Absolute |
canonical_url |
str | None
|
|
image_url |
str | None
|
|
image_alt |
str | None
|
|
version |
str | None
|
Changes whenever the item's preview
changes (an |
card |
ShareCardSchema | None
|
Content of the generated image. |
render_share_page
¶
render_share_page(
preview: SharePreviewSchema,
*,
url: str,
image_url: str | None,
image_width: int | None = None,
image_height: int | None = None,
site_name: str | None = None,
locale: str | None = None,
link_text: str = "Open",
) -> str
Write the share page of one item.
A crawler reads the tags; a human is sent to preview.redirect_url
by <meta http-equiv=refresh> and, where refresh is blocked, by the
visible link.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
preview
|
SharePreviewSchema
|
What to say about the item. |
required |
url
|
str
|
The canonical URL ( |
required |
image_url
|
str | None
|
The absolute |
required |
image_width
|
int | None
|
|
None
|
image_height
|
int | None
|
|
None
|
site_name
|
str | None
|
|
None
|
locale
|
str | None
|
|
None
|
link_text
|
str
|
Text of the visible link to |
'Open'
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The HTML document. |
Example
from tempest_fastapi_sdk.share import SharePreviewSchema page = render_share_page( ... SharePreviewSchema( ... title="Promo", ... description="Hoje", ... redirect_url="https://app.example.com/p/1", ... ), ... url="https://api.example.com/s/1", ... image_url=None, ... ) "Promo" in page False
render_qr
¶
render_qr(
url: str,
*,
logo: bytes | Path | None = None,
logo_fraction: float = DEFAULT_QR_LOGO_FRACTION,
scale: int = 10,
border: int = 4,
) -> bytes
Encode url as a PNG QR code, optionally with a logo in the middle.
Always error-correction level H and never Micro QR (segno
picks Micro QR for very short text, and phone readers generally do
not support it).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The payload, usually the share page of an item. |
required |
logo
|
bytes | Path | None
|
PNG/JPEG/WebP drawn in the middle on a white frame; transparency is kept. |
None
|
logo_fraction
|
float
|
Logo side over QR side, at most
:data: |
DEFAULT_QR_LOGO_FRACTION
|
scale
|
int
|
Pixels per module. Raise it for print instead of enlarging the PNG afterwards. |
10
|
border
|
int
|
Quiet zone in modules; 4 is what ISO/IEC 18004 asks for. |
4
|
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
The PNG. |
Raises:
| Type | Description |
|---|---|
ImportError
|
Without the |
ValueError
|
On a bad |
Example
png = render_qr("https://app.example.com/s/42") png[:4] b'\x89PNG'
make_share_router
¶
make_share_router(
resolver: ShareResolver,
*,
public_url: str,
fallback: SharePreviewSchema,
prefix: str = "/s",
renderer: ShareCardRenderer | None = None,
site_name: str | None = None,
locale: str | None = None,
link_text: str = "Open",
cache_control: str = "public, max-age=600",
tags: Sequence[str] | None = None,
dependencies: Sequence[Any] | None = None,
include_in_schema: bool = False,
) -> APIRouter
Build the share page and preview image routes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
resolver
|
ShareResolver
|
|
required |
public_url
|
str
|
Absolute |
required |
fallback
|
SharePreviewSchema
|
The preview served when the
resolver returns |
required |
prefix
|
str
|
Path prefix of the routes; starts with |
'/s'
|
renderer
|
ShareCardRenderer | None
|
Draws |
None
|
site_name
|
str | None
|
|
None
|
locale
|
str | None
|
|
None
|
link_text
|
str
|
Text of the visible link a human clicks when
|
'Open'
|
cache_control
|
str
|
|
'public, max-age=600'
|
tags
|
Sequence[str] | None
|
OpenAPI tags, when
|
None
|
dependencies
|
Sequence[Any] | None
|
Router-level dependencies (a rate limit). Crawlers send no credentials, so an auth dependency here makes every preview the error page. |
None
|
include_in_schema
|
bool
|
List the routes in OpenAPI. Off by default: they are public meta pages, not API. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
The router, to |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |