Skip to content

Python examples

Small programs built on the audiencekit package, one per thing a site or service does. Each defines the functions it is built around, so the SDK’s tests run them against a fake API, and runs as a program when started directly. They use only the standard library besides audiencekit:

Terminal window
pip install audiencekit
AUDIENCEKIT_TOKEN=akst_… AUDIENCEKIT_HOST=hotmess.social python listings_site.py
File What it shows
listings_site.py A page of the audience’s public listings, read with a service token and cached for five minutes
news_digest.py A Markdown digest of a locale’s news and its national news, for a newsletter job
facebook_sign_in.py Signing people in with Facebook on a server, one session per browser
member_actions.py What a signed-in member does: RSVP, calendar links, the door pass and reporting
community_export.py The whole community as JSON, for a static site generator
listings_site.py
"""A page of the audience's public listings, as a venue guide or a city site would show them.
AUDIENCEKIT_TOKEN=akst_… AUDIENCEKIT_HOST=hotmess.social python listings_site.py
The service token needs the ``public:read`` scope. Listings change a few times a day, so the page is cached for five
minutes rather than read on every request.
"""
from __future__ import annotations
import time
from collections.abc import Callable, Iterable
from html import escape
from wsgiref.simple_server import make_server
from zoneinfo import ZoneInfo
from audiencekit import Client, PublicListing
def render_listing(listing: PublicListing, time_zone: str = "America/Denver") -> str:
"""One listing as HTML: venues with their address, events with their time, posts with their text."""
title = escape(listing.title or "")
if listing.kind == "venue":
return f"<h2>{title}</h2><p>{escape(listing.address or '')}</p>"
if listing.kind == "event":
when = (
listing.start_at.astimezone(ZoneInfo(time_zone)).strftime("%a %b %-d, %-I:%M %p")
if listing.start_at
else ""
)
canceled = " <strong>Canceled</strong>" if listing.is_canceled else ""
return f"<h3>{title}</h3><p><time>{when}</time> at {escape(listing.venue_name or '')}{canceled}</p>"
if listing.kind == "post":
return f"<article><h3>{title}</h3><p>{escape(listing.description or '')}</p></article>"
return ""
def render_page(client: Client) -> str:
"""The whole page. "Community" listings show in full only to members, so they're left out of a public page."""
listings = [listing for listing in client.public_listings() if listing.is_public]
body = "\n".join(render_listing(listing) for listing in listings)
return f'<!doctype html><meta charset="utf-8"><title>What\'s on</title>\n{body}\n'
def cached(
render: Callable[[], str], seconds: float = 300, now: Callable[[], float] = time.monotonic
) -> Callable[[], str]:
"""Keeps the rendered page for ``seconds``, so the API is asked at most once in that time."""
page: tuple[str, float] | None = None
def read() -> str:
nonlocal page
if page is None or now() >= page[1]:
page = (render(), now() + seconds)
return page[0]
return read
def app(page: Callable[[], str]) -> Callable[..., Iterable[bytes]]:
"""A WSGI app serving the page; any WSGI server (gunicorn, uWSGI) runs it."""
def serve(environ: dict[str, object], start_response: Callable[..., object]) -> Iterable[bytes]:
try:
html = page()
except Exception as error: # shown as a 502 and logged for the operator
print(error)
start_response("502 Bad Gateway", [("Content-Type", "text/plain; charset=utf-8")])
return [b"The listings aren't available right now."]
start_response("200 OK", [("Content-Type", "text/html; charset=utf-8")])
return [html.encode()]
return serve
if __name__ == "__main__":
client = Client.from_environment()
print("http://localhost:8080")
make_server("", 8080, app(cached(lambda: render_page(client)))).serve_forever()
news_digest.py
"""A Markdown digest of a locale's news, for a newsletter or a Discord post.
AUDIENCEKIT_TOKEN=<application API key> AUDIENCEKIT_HOST=hotmess.social python news_digest.py Denver
Returns nothing for an audience without Soapbox, rather than failing.
"""
from __future__ import annotations
import sys
from audiencekit import Article, Client
def line(article: Article) -> str:
"""One article as a Markdown list item. A teaser carries only the start: the rest is on the publication's site."""
name = article.publication.name
link = f" ([read on {name}](https://github.com/lwm-luminx/audience-kit-sdk/blob/main/python/examples/{article.canonical_url}))" if article.teaser and article.canonical_url else ""
summary = f"\n {article.summary}" if article.summary else ""
disclosure = f"\n _{article.disclosure}_" if article.disclosure else ""
return f"- **{article.title}**, {article.byline} for {name}{link}{summary}{disclosure}"
def digest(client: Client, locale_name: str | None = None) -> str:
"""The digest for the locale named ``locale_name`` (or the audience's first): its news, then the national news."""
locales = client.locales()
locale = next((each for each in locales if each.name == locale_name), locales[0] if locales else None)
if locale is None:
return ""
local = client.articles(locale_id=locale.id, first=10)
national = client.national_articles(locale_id=locale.id, first=5)
sections = [f"# {locale.name} this week"]
if local:
sections.append("## Local news\n\n" + "\n".join(line(article) for article in local))
seen = {article.id for article in local}
elsewhere = [article for article in national if article.id not in seen]
if elsewhere:
sections.append("## Around the country\n\n" + "\n".join(line(article) for article in elsewhere))
return "\n\n".join(sections) + "\n" if len(sections) > 1 else ""
if __name__ == "__main__":
with Client.from_environment() as client:
print(digest(client, sys.argv[1] if len(sys.argv) > 1 else None))
facebook_sign_in.py
"""Signing people in with Facebook on a server: each browser gets its own AudienceKit session, kept server-side.
FACEBOOK_APP_ID=… AUDIENCEKIT_HOST=hotmess.social python facebook_sign_in.py
The API trades Facebook's code with the app secret, so the secret never reaches this server. Keep sessions in your
database or framework's session store in production; the dict here is for the example.
"""
from __future__ import annotations
import json
import os
import secrets
from collections.abc import Callable, Iterable
from dataclasses import dataclass, field
from http.cookies import SimpleCookie
from typing import Any
from urllib.parse import parse_qs, urlencode
from wsgiref.simple_server import make_server
import httpx
from audiencekit import AudienceKitError, Client, Configuration, Credential, DeviceDescription
REDIRECT_URI = "http://localhost:8080/auth/facebook"
@dataclass
class BrowserSession:
"""One browser's session: its AudienceKit credential, a device ID, and the state of a sign-in in progress."""
device_id: str = field(default_factory=lambda: secrets.token_hex(16))
credential: dict[str, Any] | None = None
state: str | None = None
def client_for(session: BrowserSession, configuration: Configuration, http: httpx.Client) -> Client:
"""A client acting as this browser's person: it starts from their saved credential and saves every new one. The
clients share one ``httpx.Client``, so its connections are reused across requests."""
def keep(event: str, credential: Credential | None) -> None:
session.credential = credential.to_json() if credential else None
saved = Credential.from_json(session.credential) if session.credential else None
return Client(configuration, credential=saved, http=http, on_session_change=keep)
def login_url(session: BrowserSession, facebook_app_id: str, config_id: str | None = None) -> str:
"""Facebook's login dialog, with a fresh state to check when Facebook sends the person back."""
session.state = secrets.token_urlsafe(24)
query = {
"client_id": facebook_app_id,
"redirect_uri": REDIRECT_URI,
"state": session.state,
"response_type": "code",
}
if config_id:
query["config_id"] = config_id
return f"https://www.facebook.com/v21.0/dialog/oauth?{urlencode(query)}"
def finish_sign_in(client: Client, session: BrowserSession, code: str, state: str) -> bool:
"""Trades Facebook's code for an AudienceKit session, once the state matches the one the dialog was opened with."""
expected, session.state = session.state, None
if not expected or not secrets.compare_digest(expected, state):
return False
client.sign_in_with_facebook_code(code, REDIRECT_URI, DeviceDescription(session.device_id, type="web"))
return True
def make_app(
configuration: Configuration, sessions: dict[str, BrowserSession], http: httpx.Client | None = None
) -> Callable[..., Any]:
"""The WSGI app: ``/`` says who's signed in, ``/sign-in`` opens Facebook, ``/auth/facebook`` finishes."""
shared = http or httpx.Client(timeout=30.0)
def app(environ: dict[str, Any], start_response: Callable[..., Any]) -> Iterable[bytes]:
cookie = SimpleCookie(environ.get("HTTP_COOKIE", ""))
sid = cookie["sid"].value if "sid" in cookie and cookie["sid"].value in sessions else secrets.token_urlsafe(24)
session = sessions.setdefault(sid, BrowserSession())
headers = [("Set-Cookie", f"sid={sid}; HttpOnly; SameSite=Lax; Path=/")]
path, query = environ.get("PATH_INFO", "/"), parse_qs(environ.get("QUERY_STRING", ""))
def respond(status: str, body: str = "", location: str | None = None) -> list[bytes]:
extra = [("Location", location)] if location else [("Content-Type", "text/plain; charset=utf-8")]
start_response(status, headers + extra)
return [body.encode()]
client = client_for(session, configuration, shared)
if path == "/sign-in":
branding = client.branding()
config_id = branding.facebook_login_config_id
return respond("302 Found", location=login_url(session, configuration.facebook_app_id or "", config_id))
if path == "/auth/facebook":
code, state = query.get("code", [""])[0], query.get("state", [""])[0]
if not finish_sign_in(client, session, code, state):
return respond("400 Bad Request", "That sign-in link has expired. Try again.")
# A new session ID, so the one that carried the sign-in isn't the one that carries the credential.
sessions[new_sid := secrets.token_urlsafe(24)] = sessions.pop(sid)
headers[0] = ("Set-Cookie", f"sid={new_sid}; HttpOnly; SameSite=Lax; Path=/")
return respond("302 Found", location="/")
if not client.is_signed_in:
return respond("200 OK", "Not signed in. Visit /sign-in.")
try:
me = client.me()
except AudienceKitError as error:
if error.is_unauthenticated:
return respond("302 Found", location="/sign-in")
raise
return respond("200 OK", json.dumps({"signed_in_as": me.name if me else None}))
return app
if __name__ == "__main__":
configuration = Configuration(
host=os.environ.get("AUDIENCEKIT_HOST"), facebook_app_id=os.environ["FACEBOOK_APP_ID"]
)
print("http://localhost:8080/sign-in")
make_server("", 8080, make_app(configuration, {})).serve_forever()
member_actions.py
"""What a signed-in member does on a site, in the order a night out goes: RSVP, add it to their calendar, show the
cover pass at the door, and report something they saw in chat."""
from __future__ import annotations
import time
from audiencekit import REPORT_REASONS, Client, ReportResult, cover_pass_code
from audiencekit.cover_pass import seconds_until_next_window
def going_to(client: Client, event_id: str) -> str:
"""Says they're going, and returns their answer as the API recorded it."""
return client.rsvp_event(event_id, "ATTENDING")
def calendar_links(client: Client, venue_id: str | None = None) -> dict[str, str]:
"""Links that add every event they're going to (and every event at ``venue_id``) to their own calendar."""
feed = client.follow_venue_in_calendar(venue_id) if venue_id else client.create_calendar_feed()
return {"apple_or_outlook": feed.webcal_url, "google": feed.google_url}
def door_pass(client: Client, venue_id: str, now: float | None = None) -> dict[str, object] | None:
"""The code to show at the door for tonight's cover at a venue, and how long it's good for. It changes every 30
seconds, so show it as a QR code and draw it again when ``refresh_in_seconds`` runs out; don't cache it."""
at = time.time() if now is None else now
cover = client.venue_cover(venue_id)
admission = cover.viewer_admission if cover else None
if admission is None or not admission.pass_secret or admission.status != "PAID":
return None
return {
"code": cover_pass_code(admission.id, admission.pass_secret, at),
"refresh_in_seconds": seconds_until_next_window(at),
}
def report_harassment(client: Client, message_id: str) -> ReportResult:
"""Reports a chat message as harassment and blocks whoever sent it."""
return client.report_content("MESSAGE", message_id, REPORT_REASONS[1], block=True)
community_export.py
"""The whole community as JSON, for a static site generator (Pelican, MkDocs, Hugo) to build pages from.
AUDIENCEKIT_TOKEN=<application API key> AUDIENCEKIT_HOST=hotmess.social python community_export.py > community.json
"""
from __future__ import annotations
import json
from typing import Any
from audiencekit import Client, Community
def accent(community: Community) -> str | None:
"""The audience's accent color, from its light theme."""
theme = community.audience.theme if community.audience else None
return next((token.value for token in theme.light if token.name == "accent"), None) if theme else None
def export_community(community: Community) -> dict[str, Any]:
"""The parts a site renders, flattened: venues with a map point, events with their venue's name, and the accent."""
return {
"audience": community.audience.name if community.audience else None,
"accent": accent(community),
"locales": [{"id": locale.id, "name": locale.name} for locale in community.locales],
"venues": [
{
"id": venue.id,
"name": venue.name,
"locale": venue.locale.name if venue.locale else None,
"point": (
{"latitude": point.latitude, "longitude": point.longitude}
if venue.location and (point := venue.location.coordinate)
else None
),
"tags": [tag.name for tag in venue.tags or []],
}
for venue in community.venues
if not venue.hidden
],
"events": [
{
"id": event.id,
"name": event.name,
"start_at": event.start_at.isoformat() if event.start_at else None,
"venue": event.venue_name,
}
for event in community.events
],
}
if __name__ == "__main__":
with Client.from_environment() as client:
print(json.dumps(export_community(client.community()), indent=2))