"""Stateful, network-closed Medium offline clone.
Public reading and discovery use a deliberately small synthetic corpus. All
authoring, publication, account, and community mutations are clone-local and
owned by the site-bound WebsiteBench SQLite runtime.
"""
from __future__ import annotations
import io
import json
import sqlite3
import zipfile
from pathlib import Path
from typing import Any, Mapping
from urllib.parse import quote_plus, urlencode
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response, StreamingResponse
from fastapi.staticfiles import StaticFiles
import domain
import render
import site_data
from backend import site_model
from backend.site_backend_integration import open_site_services
from websitebench.local_clone_auth import AuthError
from websitebench.site_backend import MailError
SITE_ID = "medium"
DISPLAY_NAME = "Medium"
BACKEND, AUTH = open_site_services()
for seed_account in site_data.SEED_ACCOUNTS:
AUTH.seed_account(**seed_account)
COOKIE = dict(BACKEND.session_cookie)
COOKIE_NAME = str(COOKIE.pop("name"))
STATIC_DIR = Path(__file__).resolve().parent / "static"
app = FastAPI(title=DISPLAY_NAME, docs_url=None, redoc_url=None, openapi_url=None)
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
def _session(request: Request) -> tuple[str, dict[str, Any]]:
return AUTH.ensure_session(request.cookies.get(COOKIE_NAME))
def _account(session: Mapping[str, Any]) -> dict[str, Any] | None:
account = session.get("account")
return dict(account) if account else None
def _subject(session: Mapping[str, Any]) -> str | None:
account = _account(session)
return str(account["subject_id"]) if account else None
def _cookie(response: Response, token: str) -> Response:
response.set_cookie(COOKIE_NAME, token, **COOKIE)
return response
def _html(token: str, markup: str, status: int = 200) -> HTMLResponse:
return _cookie(HTMLResponse(markup, status_code=status), token)
def _json(token: str, payload: Any, status: int = 200) -> JSONResponse:
return _cookie(JSONResponse(payload, status_code=status), token)
def _to(token: str, target: str) -> RedirectResponse:
return _cookie(RedirectResponse(render.safe_next(target), status_code=303), token)
def _signin(token: str, request: Request) -> RedirectResponse:
path = request.url.path + (f"?{request.url.query}" if request.url.query else "")
return _to(token, "/m/signin?" + urlencode({"next": path}))
def _error_json(token: str, exc: Exception) -> JSONResponse:
if isinstance(exc, domain.ValidationFailure):
return _json(token, {"ok": False, "error": str(exc), "errors": exc.errors}, 400)
if isinstance(exc, domain.PermissionDenied):
return _json(token, {"ok": False, "error": str(exc)}, 403)
if isinstance(exc, domain.NotFound):
return _json(token, {"ok": False, "error": str(exc)}, 404)
if isinstance(exc, domain.Conflict):
return _json(token, {"ok": False, "error": str(exc)}, 409)
return _json(token, {"ok": False, "error": "The local action could not be completed."}, 500)
def _owner_or_error(token: str, session: Mapping[str, Any]) -> tuple[str | None, JSONResponse | None]:
subject = _subject(session)
if not subject:
return None, _json(token, {"ok": False, "error": "Sign in to continue."}, 401)
return subject, None
async def _payload(request: Request) -> dict[str, Any]:
"""Read a mutation payload without letting a bad body abort the connection.
Page scripts, harness probes, and agent journeys reach the same endpoints
with JSON, form encodings, and empty bodies. Raising out of the handler
would make the ASGI server tear the keep-alive socket down, so an
unreadable body becomes an empty payload and the endpoint answers with its
own validation error instead.
"""
raw = await request.body()
if raw:
try:
value = json.loads(raw)
except ValueError:
value = None
if isinstance(value, Mapping):
return dict(value)
if value is None:
try:
form = await request.form()
except Exception:
return {}
return {key: value for key, value in form.items() if isinstance(value, str)}
return {}
@app.get("/health")
@app.get("/healthz")
def health() -> dict[str, str]:
return {"status": "ok", "site_id": SITE_ID}
@app.get("/__websitebench/health")
def websitebench_health() -> dict[str, str]:
return {"status": "ok"}
@app.get("/", response_class=HTMLResponse)
def home(request: Request) -> Response:
token, session = _session(request)
account = _account(session)
with BACKEND.lifecycle.connection() as connection:
stories = domain.list_public_stories(connection)
if not account:
body = '''Human stories & ideas A place to read, write, and deepen your understanding
Start reading ''' + render.join_modal()
else:
cards = "".join(render.story_card(story) for story in stories)
promo_arrow = ''' '''
body = f'''Welcome Offer Access to everything. Now 30% off. Upgrade now Staff Picks Quiet tools for deeper work 6 min read
Cities built for curiosity 4 min read
Recommended topics See more topics × Your ten-step writing starter kit Choose a clear idea, write for one reader, and begin with the smallest useful draft.
Start writing '''
return _html(token, render.layout("Medium", body, account=account, page_class="home-page account-home" if account else "home-page"))
def _public_information_page(
request: Request,
*,
title: str,
eyebrow: str,
introduction: str,
sections: tuple[tuple[str, str], ...],
actions: tuple[tuple[str, str], ...] = (),
) -> Response:
"""Render a distinct public-information destination without remote dependencies."""
token, session = _session(request)
rows = "".join(
f'{f"{render.e(heading)} " if heading else ""}{render.e(copy)}
'
for heading, copy in sections
)
links = "".join(
f'{render.e(label)} '
for index, (label, href) in enumerate(actions)
)
body = f'''{render.e(eyebrow)}
{render.e(title)} {f'{render.e(introduction)}
' if introduction else ''}{f'{links}
' if links else ''}{f'{rows}
' if rows else ''} '''
return _html(token, render.layout(f"{title} – Medium", body, account=_account(session)))
@app.get("/our-story", response_class=HTMLResponse)
@app.get("/about", response_class=HTMLResponse)
def our_story(request: Request) -> Response:
token, session = _session(request)
body = '''Everyone has a story to tell Medium is a home for human stories and ideas. Here, anyone can share knowledge and wisdom with the world—without having to build a mailing list or a following first. The internet is noisy and chaotic; Medium is quiet yet full of insight. It’s simple, beautiful, collaborative, and helps you find the right readers for whatever you have to say.
Ultimately, our goal is to deepen our collective understanding of the world through the power of writing.
We believe that what you read and write matters. Words can divide or empower us, inspire or discourage us. In a world where the most sensational and surface-level stories often win, we’re building a system that rewards depth, nuance, and time well spent. A space for thoughtful conversation more than drive-by takes, and substance over packaging.
Over 100 million people connect and share their wisdom on Medium every month. They’re software developers, amateur novelists, product designers, CEOs, and anyone burning with a story they need to get out into the world. They write about what they’re working on, what’s keeping them up at night, what they’ve lived through, and what they’ve learned that the rest of us might want to know too.
Instead of selling ads or selling your data, we’re supported by a growing community of over a million Medium members who believe in our mission. If you’re new here, start reading . Dive deeper into whatever matters to you. Find a post that helps you learn something new, or reconsider something familiar—and then write your story .
Start reading → Start writing → Become a member → '''
return _html(token, render.layout("About Medium", body, account=_account(session), page_class="about-surface"))
@app.get("/search", response_class=HTMLResponse)
def search(request: Request) -> Response:
token, session = _session(request)
query = str(request.query_params.get("q") or "").strip()
with BACKEND.lifecycle.connection() as connection:
stories = domain.list_public_stories(connection, query)
if query and not stories:
results = f''''''
elif query:
results = "".join(render.story_card(story) for story in stories)
else:
results = ''''''
body = f'''{'Search results for '+render.e(query) if query else 'Search Medium'} {results} '''
return _html(token, render.layout(f"Search{' – '+query if query else ''} – Medium", body, account=_account(session)))
@app.get("/tag/{topic}", response_class=HTMLResponse)
def tag(request: Request, topic: str) -> Response:
return search(request)
@app.get("/m/signin", response_class=HTMLResponse)
def signin_page(request: Request) -> Response:
token, session = _session(request)
if session.get("authenticated"):
return _to(token, render.safe_next(request.query_params.get("next"), "/"))
signup_intent = request.query_params.get("operation") == "register"
redirect = str(request.query_params.get("redirect") or "")
write_intent = signup_intent and (
request.query_params.get("next") == "/new-story"
or redirect.endswith("/new-story")
)
email_step = request.query_params.get("step") == "email"
email_step_href = (
"/m/signup?step=email&next=%2Fnew-story&intent=write"
if write_intent
else ("/m/signup?step=email" if signup_intent else "/m/signin?step=email")
)
return _html(
token,
render.auth_page(
signup=signup_intent,
email_step=email_step,
write_intent=write_intent,
email_step_href=email_step_href,
),
)
@app.get("/m/signup", response_class=HTMLResponse)
def signup_page(request: Request) -> Response:
token, session = _session(request)
if session.get("authenticated"):
return _to(token, "/onboarding")
write_intent = request.query_params.get("intent") == "write" or request.query_params.get("next") == "/new-story"
email_step_href = (
"/m/signup?step=email&next=%2Fnew-story&intent=write"
if write_intent
else "/m/signup?step=email"
)
return _html(
token,
render.auth_page(
signup=True,
email_step=request.query_params.get("step") == "email",
write_intent=write_intent,
email_step_href=email_step_href,
),
)
@app.get("/m/recovery", response_class=HTMLResponse)
def recovery_page(request: Request) -> Response:
"""Local-only password recovery, backed by the site's auth outbox."""
token, session = _session(request)
if session.get("authenticated"):
return _to(token, "/me/settings")
return _html(token, render.recovery_page())
@app.post("/api/auth/sign-in")
async def api_sign_in(request: Request) -> Response:
token, _ = _session(request)
data = await _payload(request)
try:
result = AUTH.sign_in(token, email=str(data.get("email", "")), password=str(data.get("password", "")))
except AuthError:
return _json(token, {"ok": False, "error": "The email or password you entered is incorrect."}, 401)
return _json(str(result["session_token"]), {"ok": True, "account": result["account"]})
@app.post("/__websitebench/session")
async def diagnostic_session(request: Request) -> Response:
"""Create only a seeded synthetic session for the local diagnostic driver."""
token, _ = _session(request)
form = await request.form()
try:
result = AUTH.sign_in(token, email=str(form.get("email", "")), password=str(form.get("password", "")))
except AuthError:
return _json(token, {"ok": False, "error": "credentials are invalid"}, 401)
return _json(str(result["session_token"]), {"ok": True, "account": result["account"]})
@app.post("/api/auth/sign-out")
def api_sign_out(request: Request) -> Response:
token, _ = _session(request)
AUTH.sign_out(token)
return _json(AUTH.create_anonymous_session(), {"ok": True})
@app.post("/api/auth/register/start")
async def api_register_start(request: Request) -> Response:
token, session = _session(request)
if session.get("authenticated"):
return _json(token, {"ok": False, "error": "Sign out before creating another account."}, 409)
data = await _payload(request)
try:
flow = AUTH.start_registration(token, email=str(data.get("email", "")), display_name=str(data.get("display_name", "")), password=str(data.get("password", "")))
local_mail = AUTH.local_mail_for_session(token, purpose="registration")
except AuthError as exc:
return _json(token, {"ok": False, "error": str(exc)}, 400)
return _json(token, {"ok": True, "flow": flow, "local_verification_code": local_mail.get("verification_code") if local_mail else None})
@app.post("/api/auth/register/verify")
async def api_register_verify(request: Request) -> Response:
token, _ = _session(request)
data = await _payload(request)
try:
AUTH.verify_registration_code(token, str(data.get("code", "")))
result = AUTH.complete_registration(token, subject_factory=domain.create_subject)
except (AuthError, domain.DomainError) as exc:
return _json(token, {"ok": False, "error": str(exc)}, 400)
return _json(str(result["session_token"]), {"ok": True, "account": result["account"]})
@app.post("/api/auth/recovery/start")
async def api_recovery_start(request: Request) -> Response:
token, session = _session(request)
if session.get("authenticated"):
return _json(token, {"ok": False, "error": "Sign out before resetting a password."}, 409)
data = await _payload(request)
try:
flow = AUTH.start_password_reset(token, email=str(data.get("email", "")))
# The offline-harbor profile deliberately keeps this local-only. The
# code is held by the session-owned fixture inbox, never persisted in
# the outbox or sent to a real recipient.
local_mail = AUTH.local_mail_for_session(token, purpose="password-reset")
except AuthError as exc:
return _json(token, {"ok": False, "error": str(exc)}, 400)
return _json(token, {
"ok": True,
"flow": {"accepted": bool(flow.get("accepted")), "message": flow.get("message")},
"mail_status": AUTH.session_mail_status(token, purpose="password-reset"),
"local_verification_code": local_mail.get("verification_code") if local_mail else None,
})
@app.post("/api/auth/recovery/verify")
async def api_recovery_verify(request: Request) -> Response:
token, _ = _session(request)
data = await _payload(request)
try:
AUTH.verify_password_reset_code(token, str(data.get("code", "")))
except AuthError as exc:
return _json(token, {"ok": False, "error": str(exc)}, 400)
return _json(token, {"ok": True, "flow": AUTH.session_flow_status(token, purpose="password-reset")})
@app.post("/api/auth/recovery/complete")
async def api_recovery_complete(request: Request) -> Response:
token, _ = _session(request)
data = await _payload(request)
try:
session_token = AUTH.complete_password_reset(token, new_password=str(data.get("password", "")))
except AuthError as exc:
return _json(token, {"ok": False, "error": str(exc)}, 400)
return _json(session_token, {"ok": True})
@app.get("/onboarding", response_class=HTMLResponse)
def onboarding(request: Request) -> Response:
token, session = _session(request)
if not _subject(session):
return _signin(token, request)
choices = "".join(f' {render.e(value)} ' for value in site_data.INTERESTS)
body = f'''Make Medium yours
What are you interested in? Choose at least two topics. You can change these local preferences later.
'''
return _html(token, render.layout("Choose your interests – Medium", body, account=_account(session), page_class="onboarding-page"))
@app.post("/api/onboarding")
async def api_onboarding(request: Request) -> Response:
token, session = _session(request)
subject, failure = _owner_or_error(token, session)
if failure:
return failure
data = await _payload(request)
try:
with BACKEND.lifecycle.connection(transaction=True) as connection:
value = domain.save_onboarding(connection, str(subject), list(data.get("interests") or []))
except domain.DomainError as exc:
return _error_json(token, exc)
return _json(token, {"ok": True, "profile": value})
@app.get("/me/lists", response_class=HTMLResponse)
def library_page(request: Request) -> Response:
token, session = _session(request)
if not _subject(session):
return _signin(token, request)
with BACKEND.lifecycle.connection() as connection:
stories = domain.list_public_stories(connection)
cards = "".join(render.story_card(story) for story in stories[:3])
body = f'''Reading list
Stories saved for later {cards or ''} '''
return _html(token, render.layout("Your library – Medium", body, account=_account(session)))
@app.get("/me/notifications", response_class=HTMLResponse)
def notifications_page(request: Request) -> Response:
token, session = _session(request)
if not _subject(session):
return _signin(token, request)
body = '''Notifications All Responses ✓ You’re all caught up. New responses and activity on your local stories will appear here.
'''
return _html(token, render.layout("Notifications – Medium", body, account=_account(session)))
@app.get("/me")
def own_profile(request: Request) -> Response:
token, session = _session(request)
account = _account(session)
if not account:
return _signin(token, request)
return _to(token, f'/@{site_data.profile_slug(account)}')
@app.get("/@{username}", response_class=HTMLResponse)
def profile_page(request: Request, username: str) -> Response:
token, session = _session(request)
profile_account = site_data.account_for_slug(username)
if profile_account is None:
return _html(token, render.error_page("Profile not found – Medium", "404", "This local writer profile is unavailable.", account=_account(session)), 404)
with BACKEND.lifecycle.connection() as connection:
stories = [story for story in domain.list_public_stories(connection) if story["owner_subject_id"] == profile_account["subject_id"]]
cards = "".join(render.story_card(story) for story in stories)
own_profile = _subject(session) == profile_account["subject_id"]
body = f'''Home Lists About {cards or 'No published stories yet.
'} '''
return _html(token, render.layout(f'{profile_account["display_name"]} – Medium', body, account=_account(session)))
@app.get("/me/following-feed/writers", response_class=HTMLResponse)
@app.get("/me/following/suggestions", response_class=HTMLResponse)
def following_page(request: Request) -> Response:
token, session = _session(request)
if not _subject(session):
return _signin(token, request)
body = '''Following Find writers and publications to follow.
N Noah Williams Writing about learning, culture, and science.
View profile '''
return _html(token, render.layout("Following – Medium", body, account=_account(session)))
@app.get("/me/stories", response_class=HTMLResponse)
@app.get("/me/stories/drafts", response_class=HTMLResponse)
def drafts(request: Request) -> Response:
token, session = _session(request)
subject = _subject(session)
if not subject:
return _signin(token, request)
with BACKEND.lifecycle.connection() as connection:
stories = domain.list_owned_stories(connection, subject)
cards = "".join(render.story_card(story, manage=True) for story in stories)
body = f''''''
return _html(token, render.layout("Your stories – Medium", body, account=_account(session)))
@app.get("/new-story")
def new_story(request: Request) -> Response:
token, session = _session(request)
subject = _subject(session)
if not subject:
return _to(token, "/m/signup?operation=register&next=/new-story&intent=write")
with BACKEND.lifecycle.connection(transaction=True) as connection:
blank = connection.execute("SELECT story_id FROM medium_stories WHERE owner_subject_id=? AND status='draft' AND title='' AND body='' ORDER BY created_at DESC LIMIT 1", (subject,)).fetchone()
story_id = str(blank["story_id"]) if blank else domain.create_story(connection, subject)
return _to(token, f"/p/{story_id}/edit")
@app.get("/p/{story_id}/edit", response_class=HTMLResponse)
def story_editor(request: Request, story_id: str) -> Response:
token, session = _session(request)
subject = _subject(session)
if not subject:
return _signin(token, request)
try:
with BACKEND.lifecycle.connection() as connection:
story = domain.owned_story(connection, subject, story_id)
media = domain.story_media(connection, story_id)
revisions = domain.story_revisions(connection, subject, story_id)
except domain.PermissionDenied:
return _html(token, render.error_page("Permission required – Medium", "Permission required", "This draft belongs to another local author.", account=_account(session)), 403)
except domain.NotFound:
return _html(token, render.error_page("Story not found – Medium", "404", "This story is unavailable. Your other saved drafts are still safe.", account=_account(session)), 404)
return _html(token, render.editor(story, media, revisions, _account(session) or {}))
@app.get("/p/{story_id}", response_class=HTMLResponse)
def story_page(request: Request, story_id: str) -> Response:
token, session = _session(request)
subject = _subject(session)
try:
with BACKEND.lifecycle.connection() as connection:
story = domain.get_story(connection, story_id)
if story["status"] != "published" and story["owner_subject_id"] != subject:
raise domain.PermissionDenied("This story is not public.")
interactions = domain.engagement(connection, story_id)
except domain.PermissionDenied:
return _html(token, render.error_page("Story unavailable – Medium", "Private story", "Sign in as the story owner or return to available stories.", account=_account(session)), 403)
except domain.NotFound:
return _html(token, render.error_page("Page not found – Medium", "404", "You can find (just about) anything on Medium — apparently even a page that doesn’t exist.", account=_account(session)), 404)
return _html(token, render.public_story(story, interactions, account=_account(session), owner=story["owner_subject_id"] == subject))
@app.get("/api/stories/{story_id}")
def api_story(request: Request, story_id: str) -> Response:
token, session = _session(request)
subject, failure = _owner_or_error(token, session)
if failure:
return failure
try:
with BACKEND.lifecycle.connection() as connection:
story = domain.owned_story(connection, str(subject), story_id)
value = {"story": story, "media": domain.story_media(connection, story_id), "revisions": domain.story_revisions(connection, str(subject), story_id)}
except domain.DomainError as exc:
return _error_json(token, exc)
return _json(token, {"ok": True, **value})
@app.put("/api/stories/{story_id}")
async def api_save_story(request: Request, story_id: str) -> Response:
token, session = _session(request)
subject, failure = _owner_or_error(token, session)
if failure:
return failure
data = await _payload(request)
try:
revision = int(data.get("expected_revision", 0))
with BACKEND.lifecycle.connection(transaction=True) as connection:
story = domain.save_story(connection, str(subject), story_id, data, expected_revision=revision)
except (ValueError, domain.DomainError) as exc:
return _error_json(token, exc if isinstance(exc, domain.DomainError) else domain.ValidationFailure({"revision": "Reload the saved version before editing."}))
return _json(token, {"ok": True, "story": story, "message": "Saved"})
@app.post("/api/stories/{story_id}/lifecycle")
async def api_story_lifecycle(request: Request, story_id: str) -> Response:
token, session = _session(request)
subject, failure = _owner_or_error(token, session)
if failure:
return failure
data = await _payload(request)
try:
with BACKEND.lifecycle.connection(transaction=True) as connection:
story = domain.transition_story(connection, str(subject), story_id, str(data.get("action", "")), scheduled_at=str(data.get("scheduled_at", "")))
except domain.DomainError as exc:
return _error_json(token, exc)
return _json(token, {"ok": True, "story": story, "message": f"Story {story['status']}."})
@app.post("/api/stories/{story_id}/media")
async def api_add_media(request: Request, story_id: str) -> Response:
token, session = _session(request)
subject, failure = _owner_or_error(token, session)
if failure:
return failure
try:
form = await request.form()
upload = form.get("media")
if upload is None or not hasattr(upload, "read"):
raise domain.ValidationFailure({"media": "Choose an image. Your saved story was not changed."})
content = await upload.read()
with BACKEND.lifecycle.connection(transaction=True) as connection:
media_id = domain.add_media(connection, str(subject), story_id, filename=str(getattr(upload, "filename", "image")), mime_type=str(getattr(upload, "content_type", "")), alt_text=str(form.get("alt_text", "")), content=content)
except domain.DomainError as exc:
return _error_json(token, exc)
return _json(token, {"ok": True, "media_id": media_id, "message": "Image added."})
@app.delete("/api/stories/{story_id}/media/{media_id}")
def api_remove_media(request: Request, story_id: str, media_id: str) -> Response:
token, session = _session(request)
subject, failure = _owner_or_error(token, session)
if failure:
return failure
try:
with BACKEND.lifecycle.connection(transaction=True) as connection:
domain.remove_media(connection, str(subject), story_id, media_id)
except domain.DomainError as exc:
return _error_json(token, exc)
return _json(token, {"ok": True, "message": "Image removed."})
@app.post("/api/stories/{story_id}/responses")
async def api_response(request: Request, story_id: str) -> Response:
token, session = _session(request)
subject, failure = _owner_or_error(token, session)
if failure:
return failure
data = await _payload(request)
try:
with BACKEND.lifecycle.connection(transaction=True) as connection:
response_id = domain.add_response(connection, str(subject), story_id, str(data.get("body", "")), str(data.get("parent_id", "")))
except domain.DomainError as exc:
return _error_json(token, exc)
return _json(token, {"ok": True, "response_id": response_id})
@app.post("/api/stories/{story_id}/clap")
def api_clap(request: Request, story_id: str) -> Response:
token, session = _session(request)
subject, failure = _owner_or_error(token, session)
if failure:
return failure
try:
with BACKEND.lifecycle.connection(transaction=True) as connection:
active = domain.toggle_clap(connection, str(subject), story_id)
count = domain.engagement(connection, story_id)["claps"]
except domain.DomainError as exc:
return _error_json(token, exc)
return _json(token, {"ok": True, "active": active, "count": count})
@app.post("/api/stories/{story_id}/highlights")
async def api_highlight(request: Request, story_id: str) -> Response:
token, session = _session(request)
subject, failure = _owner_or_error(token, session)
if failure:
return failure
data = await _payload(request)
try:
with BACKEND.lifecycle.connection(transaction=True) as connection:
domain.add_highlight(connection, str(subject), story_id, str(data.get("quote", "")))
except domain.DomainError as exc:
return _error_json(token, exc)
return _json(token, {"ok": True, "message": "Highlight saved."})
@app.get("/me/publications/new", response_class=HTMLResponse)
def publication_create_page(request: Request) -> Response:
token, session = _session(request)
subject = _subject(session)
if not subject:
return _signin(token, request)
with BACKEND.lifecycle.connection() as connection:
publications = domain.list_publications(connection, subject)
rows = "".join(f'{render.e(item["name"])} {render.e(item["description"])}
Manage publication ' for item in publications)
body = f'''Your publications Publication settings are stored only in this offline fixture.
{rows}
'''
return _html(token, render.layout("Your publications – Medium", body, account=_account(session)))
@app.post("/api/publications")
async def api_create_publication(request: Request) -> Response:
token, session = _session(request)
subject, failure = _owner_or_error(token, session)
if failure:
return failure
data = await _payload(request)
try:
with BACKEND.lifecycle.connection(transaction=True) as connection:
publication_id = domain.create_publication(connection, str(subject), str(data.get("name", "")), str(data.get("description", "")))
except domain.DomainError as exc:
return _error_json(token, exc)
return _json(token, {"ok": True, "publication_id": publication_id})
@app.get("/publication/{publication_id}/settings", response_class=HTMLResponse)
def publication_settings(request: Request, publication_id: str) -> Response:
token, session = _session(request)
subject = _subject(session)
if not subject:
return _signin(token, request)
try:
with BACKEND.lifecycle.connection() as connection:
item = domain.publication_details(connection, subject, publication_id)
except domain.DomainError as exc:
status = 403 if isinstance(exc, domain.PermissionDenied) else 404
return _html(token, render.error_page("Publication unavailable – Medium", "Publication unavailable", str(exc), account=_account(session)), status)
tabs = "".join(f'{tab.title()} ' for tab in site_data.PUBLICATION_TABS)
member_rows = "".join(f'''
{render.e(row['display_name'])} owner editor writer viewer Save role ''' for row in item["members"])
subscriber_rows = "".join(f'{render.e(row["display_name"])} ' for row in item["subscribers"])
newsletter_rows = "".join(f'{render.e(row["subject"])} · {render.e(row["status"])} ' for row in item["newsletters"])
body = f''''''
return _html(token, render.layout(f"{item['name']} settings – Medium", body, account=_account(session)))
@app.put("/api/publications/{publication_id}/{tab}")
async def api_save_publication(request: Request, publication_id: str, tab: str) -> Response:
token, session = _session(request)
subject, failure = _owner_or_error(token, session)
if failure:
return failure
data = await _payload(request)
try:
with BACKEND.lifecycle.connection(transaction=True) as connection:
item = domain.save_publication(connection, str(subject), publication_id, tab, data)
except domain.DomainError as exc:
return _error_json(token, exc)
return _json(token, {"ok": True, "publication": item, "message": f"{tab.title()} settings saved."})
@app.post("/api/publications/{publication_id}/roles")
async def api_role(request: Request, publication_id: str) -> Response:
token, session = _session(request)
subject, failure = _owner_or_error(token, session)
if failure:
return failure
data = await _payload(request)
try:
with BACKEND.lifecycle.connection(transaction=True) as connection:
domain.change_role(connection, str(subject), publication_id, str(data.get("member_subject", "")), str(data.get("role", "")))
except domain.DomainError as exc:
return _error_json(token, exc)
return _json(token, {"ok": True, "message": "Contributor role saved."})
@app.post("/api/publications/{publication_id}/newsletter")
async def api_newsletter(request: Request, publication_id: str) -> Response:
token, session = _session(request)
subject, failure = _owner_or_error(token, session)
if failure:
return failure
data = await _payload(request)
account = _account(session) or {}
try:
with BACKEND.lifecycle.connection(transaction=True) as connection:
campaign = domain.prepare_newsletter(connection, str(subject), publication_id, str(data.get("subject", "")), str(data.get("body", "")))
job = BACKEND.mail.enqueue("newsletter", str(account.get("email_normalized", "author@medium.local")), {"subject": campaign["subject"], "summary": campaign["body"]}, idempotency_key=f"newsletter:{campaign['campaign_id']}", simulation=True, connection=connection)
connection.execute("UPDATE medium_newsletters SET mail_id=? WHERE campaign_id=?", (job["mail_id"], campaign["campaign_id"]))
except (domain.DomainError, MailError) as exc:
mapped = exc if isinstance(exc, domain.DomainError) else domain.Conflict(str(exc))
return _error_json(token, mapped)
return _json(token, {"ok": True, "campaign": {**campaign, "mail_id": job["mail_id"]}, "message": "Newsletter queued in the local outbox. No email was sent."})
@app.get("/me/stats", response_class=HTMLResponse)
def stats_page(request: Request) -> Response:
token, session = _session(request)
subject = _subject(session)
if not subject:
return _signin(token, request)
with BACKEND.lifecycle.connection() as connection:
value = domain.stats(connection, subject)
rows = "".join(f'{render.e(row["title"] or "Untitled story")} {render.e(row["status"])} {row["reads"]} {row["claps"]} {row["responses"]} ' for row in value["stories"])
body = f'''Your story stats {value['published']} Published {value['drafts']} Drafts {value['claps']} Claps {value['responses']} Responses Story Status Reads Claps Responses {rows}
'''
return _html(token, render.layout("Your stats – Medium", body, account=_account(session)))
@app.get("/me/stories/import", response_class=HTMLResponse)
def import_page(request: Request) -> Response:
token, session = _session(request)
if not _subject(session):
return _signin(token, request)
body = ''''''
return _html(token, render.layout("Import a story – Medium", body, account=_account(session)))
@app.post("/api/import")
async def api_import(request: Request) -> Response:
token, session = _session(request)
subject, failure = _owner_or_error(token, session)
if failure:
return failure
data = await _payload(request)
try:
with BACKEND.lifecycle.connection(transaction=True) as connection:
value = domain.import_story(connection, str(subject), str(data.get("url", "")))
except domain.DomainError as exc:
return _error_json(token, exc)
return _json(token, {"ok": True, **value, "message": "Local story imported as a draft."})
@app.get("/me/settings", response_class=HTMLResponse)
def settings_page(request: Request) -> Response:
token, session = _session(request)
subject = _subject(session)
if not subject:
return _signin(token, request)
with BACKEND.lifecycle.connection(transaction=True) as connection:
profile = domain.profile(connection, subject)
body = f''''''
return _html(token, render.layout("Settings – Medium", body, account=_account(session)))
@app.put("/api/settings/{tab}")
async def api_settings(request: Request, tab: str) -> Response:
token, session = _session(request)
subject, failure = _owner_or_error(token, session)
if failure:
return failure
data = await _payload(request)
try:
with BACKEND.lifecycle.connection(transaction=True) as connection:
value = domain.save_preferences(connection, str(subject), data, tab)
except domain.DomainError as exc:
return _error_json(token, exc)
return _json(token, {"ok": True, "profile": value, "message": f"{tab.title()} preferences saved."})
@app.get("/me/export")
def export_account(request: Request) -> Response:
token, session = _session(request)
subject = _subject(session)
if not subject:
return _signin(token, request)
with BACKEND.lifecycle.connection() as connection:
payload = {"site_id": SITE_ID, "profile": domain.profile(connection, subject), "stories": domain.list_owned_stories(connection, subject), "publications": domain.list_publications(connection, subject)}
stream = io.BytesIO()
with zipfile.ZipFile(stream, "w", zipfile.ZIP_DEFLATED) as archive:
archive.writestr("medium-local-export.json", json.dumps(payload, ensure_ascii=False, indent=2))
stream.seek(0)
response = StreamingResponse(stream, media_type="application/zip", headers={"Content-Disposition": 'attachment; filename="medium-local-export.zip"'})
return _cookie(response, token)
@app.get("/plans", response_class=HTMLResponse)
def plans_page(request: Request) -> Response:
token, session = _session(request)
cards = '''Free $0 Read and write in the local fixture.
Choose Free Medium Member $5/month Preview a monthly membership selection.
Choose monthly Annual Member $50/year Preview an annual membership selection.
Choose annual Partner Program Eligibility review Record interest before finalization.
Review eligibility '''
body = f'''Support human stories Selections remain local and stop before finalization. No card, bank, or wallet field exists.
{cards}
'''
return _html(token, render.layout("Medium membership", body, account=_account(session)))
@app.post("/api/plans")
async def api_plan(request: Request) -> Response:
token, session = _session(request)
subject, failure = _owner_or_error(token, session)
if failure:
return failure
data = await _payload(request)
try:
with BACKEND.lifecycle.connection(transaction=True) as connection:
value = domain.save_plan(connection, str(subject), str(data.get("plan", "")))
except domain.DomainError as exc:
return _error_json(token, exc)
return _json(token, {"ok": True, "plan": value["active_plan"], "price": value["active_plan_price"], "message": "Selection saved. Finalization is unavailable in this offline clone."})
@app.get("/membership", response_class=HTMLResponse)
def membership_page(request: Request) -> Response:
token, session = _session(request)
body = ''''''
return _html(token, render.layout("Membership – Medium", body, account=_account(session), page_class="source-error-surface membership-error-surface"))
@app.get("/hc/en-us", response_class=HTMLResponse)
@app.get("/help", response_class=HTMLResponse)
def help_page(request: Request) -> Response:
token, session = _session(request)
query = str(request.query_params.get("q") or "").strip()
matches = tuple(
(title, text, articles) for title, text, articles in site_data.HELP_TOPICS
if not query or query.lower() in f"{title} {text} {' '.join(articles)}".lower()
)
category_icons = (
' ',
' ',
' ',
' ',
' ',
' ',
)
cards = "".join(
f'{category_icons[index % len(category_icons)]} '
for index, (title, text, articles) in enumerate(matches)
)
result_note = f'{len(matches)} help topic{"s" if len(matches) != 1 else ""} for “{render.e(query)}”.
' if query else ""
empty_note = f'No help topics found for “{render.e(query)}” Try a broader account, reading, writing, or privacy question.
Browse all help topics ' if query and not matches else ""
body = f'''{result_note}{f'{cards}
' if cards else empty_note} '''
return _html(token, render.layout("Medium Help Center", body, account=_account(session), page_class="help-center-surface"))
@app.get("/status", response_class=HTMLResponse)
def status_page(request: Request) -> Response:
token, session = _session(request)
uptime = "".join(' ' for _ in range(72))
calendar_days = "".join(f'{day} ' for day in range(1, 32))
body = f'''✓ We’re fully operationalWe’re not aware of any issues affecting our systems.
System status ‹ May 2026 - Aug 2026 › ✓ Web Services 3 components⌄ 100% uptime
{uptime}
✓ Mobile Apps 2 components⌄ 100% uptime
{uptime}
Powered by incident.io
Privacy policy · Terms of service
'''
return _html(token, render.layout("Medium Status", body, account=_account(session), page_class="status-surface"))
@app.get("/careers", response_class=HTMLResponse)
@app.get("/jobs-at-medium/work-at-medium-959d1a85284e", response_class=HTMLResponse)
def careers_page(request: Request) -> Response:
token, session = _session(request)
body = '''Jobs at Medium
Medium · Careers · Jobs
Careers at Medium Help us build the best place to read and write on the internet. M Jobs @ Medium 3 min read · Jun 7, 2023
♡ — ↗
IMPORTANT NOTE: Medium has been made aware of a scam that involves offering people jobs at Medium. Please do not engage with offers that look similar to this. All our open positions are available here.
View all open positions
At Medium, we believe in the power of words — and we’re on a mission to bring the world’s expertise to life through memorable storytelling. Our platform rewards great writing and puts power back in the hands of readers. Medium’s subscription model means we rely on our members, not ads. We’re looking for teammates who are inspired by our mission, who are deeply thoughtful and empathetic, and who are passionate about the future of online publishing. Sound like you? Keep reading!
Note: Medium only hires and communicates via greenhouse.io, our third-party recruiting platform. If you you receive job offers for Medium via LinkedIn or other platforms, it may be a scam; please verify it by contacting us at help.medium.com.
· · ·
Why work at Medium A meaningful mission From our engineers to our content ops team, employees at Medium (aka “Medians”) are driven by passion, vision, and purpose. We believe in building a high-quality, open platform for sharing ideas — free from harassment, hate speech, and other harmful content. We strive to create a diverse, inclusive place for everyone to feel seen, safe, and supported, both on our product and within our organization.
Remote-first culture Collaborate with colleagues from Paris to Portland: Medium is a 100% remote workplace. We’ll provide you with what you need to do your best work, including a stipend for home office expenses, Wi-Fi reimbursement, and a local co-working space membership. (We also know how valuable it is to meet your team IRL, so we hold an all-company retreat twice a year.)
A creative environment We’re building a culture, not just a product. We believe in experimentation, innovation, and collaboration. We give hi5s and lightning talks and all-company presentations about the ambitious challenges we’re tackling. We share travel photos in our Slack #watercooler channel and craft fun playlists for Thursday writing hours. We question ideas in product workshops, learn from the expertise of our colleagues, and create new things together.
Generous benefits Comprehensive health insurance, 401(k) plans, parental leave, and unlimited paid time off are just the start. Our values show up in your benefits: We provide support for your wellbeing at home, education and professional development, financial advising, mental health support, and more.
· · ·
Join Our Team View all open positions
Read our guidance on AI use for candidates . We believe human ideas have the power to change how people think, for the better. That belief shapes how we hire. We use AI tools ourselves, but we’ve thought carefully about where it adds value and where it gets in the way of something important.
Learn more about Medium The Medium Blog The official source of news and updates about Medium medium.com Me Medium + Careers + Jobs +
♡ — ↗ ☐
Published in Jobs at Medium 4.7K followers · Last published Apr 21, 2026 Keep up to date with our job openings
Written by Jobs @ Medium 8.8K followers · 21 following
'''
return _html(token, render.layout("Medium", body, account=_account(session), page_class="careers-surface"))
@app.get("/press", response_class=HTMLResponse)
def press_page(request: Request) -> Response:
return _public_information_page(
request, title="Press", eyebrow="Medium",
introduction="", sections=(),
)
@app.get("/blog", response_class=HTMLResponse)
def blog_page(request: Request) -> Response:
token, session = _session(request)
body = '''Me
The Medium Blog 3.4M followers · 5+ editors
Product News Latest Newsletter ✉
Get the best of Medium delivered to you weekly. Subscribe '''
return _html(
token,
render.layout(
"The Medium Blog",
body,
account=_account(session),
page_class="medium-blog-surface",
),
)
@app.get("/store/medium/", response_class=HTMLResponse)
@app.get("/store", response_class=HTMLResponse)
def store_page(request: Request) -> Response:
token, session = _session(request)
products = (
("TK Merch", "Max Heavyweight Garment Dye Tee", "$25.00", "store-product-1.webp", "sand"),
("", "Reclaimist Pullover Hoodie", "$40.00", "store-product-2.webp", "black"),
("", "Classic Tie Dye Tee", "$24.05", "store-product-3.webp", "colors"),
("Word Cup", "Coffee Mug", "$12.25", "store-product-4.webp", "white"),
("Medium Sweatshirt", "Softstyle Crewneck Sweatshirt", "$29.25", "store-product-5.webp", "white"),
("Medium Wordmark Hoodie", "Heavyweight Pullover Hoodie", "$44.00", "store-product-6.webp", "black"),
)
product_cards = ""
for product_index, (group, name, price, image, swatches) in enumerate(products):
if product_index < 3:
media = f' '
else:
media = f'
'
product_cards += f'''{render.e(group)} {media}{render.e(name)} {render.e(price)}
'''
footer_columns = (
("Sell online", "Limited edition campaign", "On-demand merch store", "Personal fundraiser"),
("Explore", "Shop the marketplace", "Support a cause", "Product catalog", "Design templates"),
("Nonprofits", "For nonprofits", "Nonprofit merch stores", "Peer-to-peer fundraising"),
("Creators", "For creators", "Discover top creators", "Sell with Merch Shelf", "YouTube creators"),
("Resources", "Blog", "Help center", "Order custom shirts", "Pricing calculator", "Request a custom design", "Stories", "Track my order", "Sitemap"),
("Company", "About", "Careers", "Contact", "Reviews", "Sustainability"),
("Legal", "Accessibility", "Privacy", "Cookie policy", "Cookie preferences", "Terms & conditions", "Do not share or sell my data"),
)
footer_lists = "".join(
f'''{render.e(items[0])} {"".join(f'{render.e(item)} ' for item_index, item in enumerate(items[1:]))} '''
for index, items in enumerate(footer_columns)
)
cookie_panel = '''We use essential cookies to make our site work. With your consent, we may also use non-essential cookies to improve user experience, personalize content, customize advertisements, and analyze website traffic. For these reasons, we may share your site usage data with our social media, advertising, and analytics partners. By clicking ”Accept,” you agree to our website's cookie use as described in our Cookie Policy . You can change your cookie settings at any time by clicking “Preferences .”
Preferences Decline Accept
'''
store_menu = ''''''
body = f'''{cookie_panel}It looks like your browser is outdated. Please update to the latest version in order to get a better experience.
{store_menu} '''
return _html(token, render.layout("Bonfire - Design your own shirt on material you’ll love", body, account=_account(session), page_class="store-surface"))
@app.get("/start/intent", response_class=HTMLResponse)
@app.get("/start/intent/", response_class=HTMLResponse)
def store_start_intent(request: Request) -> Response:
"""Keep Bonfire's primary campaign-builder handoff inside the clone."""
token, session = _session(request)
body = '''GET STARTED
What would you like to create? Choose a starting point for your local merch idea. This offline clone stops before account creation, payment, publishing, or fulfillment.
← Back to the Medium store '''
return _html(token, render.layout("Get started – Bonfire", body, account=_account(session), page_class="store-surface store-intent-surface"))
@app.get("/privacy", response_class=HTMLResponse)
@app.get("/medium-privacy-policy-f03bf92035c9", response_class=HTMLResponse)
@app.get("/policy/medium-privacy-policy-f03bf92035c9", response_class=HTMLResponse)
def privacy_page(request: Request) -> Response:
token, session = _session(request)
body = ''''''
return _html(token, render.layout("Medium Privacy Policy", body, account=_account(session), page_class="source-error-surface"))
@app.get("/rules", response_class=HTMLResponse)
@app.get("/medium-rules-30e5502c4eb4", response_class=HTMLResponse)
@app.get("/policy/medium-rules-30e5502c4eb4", response_class=HTMLResponse)
def rules_page(request: Request) -> Response:
token, session = _session(request)
body = ''''''
return _html(token, render.layout("Medium Rules", body, account=_account(session), page_class="source-error-surface"))
@app.get("/terms", response_class=HTMLResponse)
@app.get("/medium-terms-of-service-9db0094a1e0f", response_class=HTMLResponse)
@app.get("/policy/medium-terms-of-service-9db0094a1e0f", response_class=HTMLResponse)
def terms_page(request: Request) -> Response:
token, session = _session(request)
rows = "".join(
f"<{tag}>{render.e(copy)}{tag}>"
for tag, copy in site_data.TERMS_ARTICLE
)
action_row = ''''''
body = f'''Terms And Conditions + Terms + Medium +
Medium Terms of Service Effective: September 1, 2020 M Medium 12 min read · Sep 1, 2020
{action_row}{rows}
Terms And Conditions Terms Medium
{action_row}Me Published in Medium Policy 45K followers · Last published Nov 8, 2021 Terms of Service, Rules, and Policies
M Written by Medium 1.5M followers · 34 following Everyone’s stories and ideas
'''
return _html(token, render.layout("Medium Terms of Service", body, account=_account(session), page_class="terms-surface"))
@app.get("/medium/", response_class=HTMLResponse)
@app.get("/text-to-speech", response_class=HTMLResponse)
def text_to_speech_page(request: Request) -> Response:
token, session = _session(request)
speechify_columns = (
("Text to Speech", "iPhone & iPad Apps", "Android App", "Mac App", "Windows App", "Web App", "Chrome Extension", "Edge Add-on", "Download"),
("For Creators", "AI Voice Generator", "Dubbing", "Voice Cloning", "Speechify Work"),
("For Business", "Speechify for Developers", "Teams", "Education", "Text to Speech API Docs", "Voice Agents API Docs"),
("Company", "About", "Contact", "Blog", "Careers", "Affiliates", "Help", "Status", "Press", "Brand Kit"),
)
speechify_links = "".join(
f'''{render.e(items[0])} {"".join(f'{render.e(item)} ' for item_index, item in enumerate(items[1:]))} '''
for column, items in enumerate(speechify_columns)
)
recommended = ("Dictation & Voice Typing", "PDF Text to Speech Android", "Female Voice Generator", "Top Dyslexia Reading Programs", "Text to Speech Anime", "PDF Audio Reader", "Text to Speech Chrome Extension", "PDF Read Aloud", "Texto a Voz", "Voice AI Assistant", "Text to Speech Reader", "Male Voice Generator", "Robot Voice Generator", "AI Voice Changer", "Can Google Docs Read to Me", "Hindi Text to Speech", "AI Voice Generator", "Leitor de Texto")
languages = ("العربية", "Magyar", "中文 (简体)", "中文 (台灣)", "中文 (简体 中国大陆)", "Čeština", "Dansk", "Nederlands", "Français", "Suomi", "Deutsch", "हिन्दी", "Italiano", "日本語", "한국어", "Norsk bokmål", "Polski", "Português Brasileiro", "Русский", "Українська", "Español", "Español (México)", "Svenska", "ไทย", "Türkçe", "Tiếng Việt", "Română", "Português", "Български", "ქართული", "Slovenčina", "Slovenščina", "Eesti", "Hrvatski", "Ελληνικά", "Lietuvių", "עברית", "Bahasa Indonesia", "বাংলা", "Català", "Bahasa Melayu", "اردو")
speechify_menu = ''''''
body = f''' Speechify is Launching Voice Typing Dictation › {speechify_menu}Home / Medium members can listen to any Medium story with the Speechify Play Button
Medium members can listen to any Medium story with the Speechify Play Button. At Medium and Speechify, we’re always exploring new ways to make content more accessible. That’s why we’re excited to share that Speechify is available to all Medium members with the launch of Medium’s Listen feature. Any Medium member can click the “Listen” button at the top of most stories to hear an audio version read aloud from a number of narrators. Users who aren’t Medium members will be invited to sign up for membership.
Since the launch of our partnership, Medium members have told us that audio has helped them consume more stories than ever before – up to three times as many. Audio helps people listen to Medium articles during the day when they normally wouldn’t be reading: while going on walks, commuting, exercising, doing chores, doing other things on their computer, or even as they fall asleep.
We’ve also heard many members tell us they retain information better when they have a chance to listen and read at the same time. This is a new way of consuming content that our partnership supports – Speechify highlights text as it reads the audio out loud to you.
“When working out, I used to read on my phone between sets. Now, it’s so much easier with audio — I can listen to many more articles than I could read before.” — Jess, Medium listener
From everything we’ve heard, we believe the Speechify play button on Medium can make your experience with Medium more enjoyable and flexible.
A Magical Way to Read More If you love reading, you probably have a long list of articles bookmarked. You can now use the Listen feature to make your way through that list faster. Speechify also allows you to change your listening speed. Some users listen to articles at 2-3x the normal listening speed. You can listen to articles at up to 4.5x the normal speed. Speed listening is a productivity hack for many, and we’re excited to make it easier for you.
A Tool for Proofreading We’ve heard that writers find the Listen feature helpful when they’re proofreading their drafts. Sentences often sound different when you read them out loud, and we’re excited to help our community of creators improve the stories they bring to life. To listen to one of your drafts, you can click the “…” button in Medium’s web editor, then select “share draft link,” visit that link yourself, and click the Listen button.
Making Reading Easy By some estimates, one in five people faces dyslexia, which can make traditional reading difficult. Many people also have visual impairment. Through our listening option, we aim to lower the barrier to learning and delight across Medium.
How You Can Listen to Medium with Speechify You can find the Listen button at the top of a Medium story. When you press this button via web browser, as a logged-in Medium member, the story text is read to you and you’ll see the words highlighted as you go.
We all have our own tastes. If you’d like to listen to a voice other than the default option, you can select a new one by clicking the voice button in the bottom left corner.
In the bottom right corner, you can click the speed button to adjust the playback speed from 0.5x to 4.5x.
Happy listening!
– Team Medium & Team Speechify
Choose your language to get the best Speechify experience ◉ English ⌄ Continue × '''
return _html(token, render.layout("Medium Members Can Listen To Any Medium Story With The Speechify Play Button | Speechify", body, account=_account(session), page_class="speechify-surface"))
@app.get("/api/state")
def api_state(request: Request) -> Response:
token, session = _session(request)
subject = _subject(session)
value: dict[str, Any] = {"authenticated": bool(subject), "account": _account(session)}
if subject:
with BACKEND.lifecycle.connection() as connection:
value.update({"profile": domain.profile(connection, subject), "stories": domain.list_owned_stories(connection, subject), "stats": domain.stats(connection, subject)})
return _json(token, value)
@app.post("/__websitebench/reset")
async def reset(request: Request) -> Response:
data = await _payload(request)
if data.get("site_id") != SITE_ID:
return JSONResponse({"ok": False, "error": "site_id confirmation is required"}, status_code=400)
AUTH.reset_site_state(site_reset=site_model.site_reset, seed_accounts=site_data.SEED_ACCOUNTS)
return _json(AUTH.create_anonymous_session(), {"ok": True, "site_id": SITE_ID})
@app.get("/{missing_path:path}", response_class=HTMLResponse)
def not_found(request: Request, missing_path: str = "") -> Response:
token, session = _session(request)
return _html(token, render.error_page("Page not found – Medium", "404", "You can find (just about) anything on Medium — apparently even a page that doesn’t exist.", account=_account(session)), 404)
if __name__ == "__main__":
import os
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=int(os.environ.get("PORT", "8003")), log_level="info")