CURAS / app /main.py
stevafernandes's picture
Multi-select areas, colour-coded area tags, Creighton students only, titles removed, Creighton blue
4f5fdec verified
Raw History Blame Contribute Delete
30.6 kB
"""CURAS Research Database: FastAPI application.
Public pages: browse approved listings, submit a new listing or an update.
Admin pages: sign in with the shared password, review and approve or reject
submissions, edit, retire or restore listings, export CSV.
Route handlers are plain functions, so FastAPI runs them in its thread pool
and a slow database call never blocks the event loop for other visitors.
"""
from __future__ import annotations
import csv
import datetime as dt
import io
import logging
import threading
import time
from pathlib import Path
from typing import Optional
from urllib.parse import urlencode
import jinja2
from fastapi import Depends, FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse, RedirectResponse, Response, StreamingResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from starlette.datastructures import FormData
from starlette.exceptions import HTTPException as StarletteHTTPException
from . import services
from .config import Settings, get_settings
from .db import Db, DbError, check_uuid
from .fields import (CONTENT_FIELDS, ELIGIBILITY_NOTE, FIELD_KEYS, FIELDS_BY_KEY, SUBMITTER_FIELDS,
SUMMARY_KEYS, area_color, split_list)
from .normalize import split_known
from .security import (SESSION_COOKIE, FormTokens, RateLimiter, SessionManager, client_ip,
password_matches)
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
log = logging.getLogger("curas.web")
BASE_DIR = Path(__file__).resolve().parent
APP_TITLE = "CURAS Research Database"
CONTACT_EMAIL = "CURAS@creighton.edu"
MAX_BODY_BYTES = 1_000_000 # the largest legitimate form is well under 100 KB
SUBMIT_LIMIT = (30, 3600) # stored submissions per client address per hour
SUBMIT_GLOBAL_LIMIT = (300, 3600) # stored submissions from everyone per hour (queue protection)
LOGIN_LIMIT = (5, 15 * 60) # failed sign-ins per client address per 15 minutes
FLASH = {
"approved": "Submission approved. The listing is now public.",
"approved_retired": "Submission approved and the listing updated. The listing is still retired; use Restore to show it publicly.",
"rejected": "Submission rejected.",
"saved": "Listing saved.",
"created": "Listing created and published.",
"retired": "Listing retired. It is no longer shown publicly.",
"restored": "Listing restored and shown publicly again.",
"signed_out": "You have signed out.",
}
TOKEN_MESSAGE = ("Your form session had expired, so nothing was sent. Your entries are still here: "
"check them and submit again.")
def fmt_date(value) -> str:
"""'October 8, 2026' from an ISO date."""
if not value:
return ""
try:
d = dt.date.fromisoformat(str(value)[:10])
except ValueError:
return str(value)
return f"{d.strftime('%B')} {d.day}, {d.year}"
def fmt_datetime(value) -> str:
"""'October 8, 2026 00:04 CDT' in the configured zone from an ISO timestamp."""
if not value:
return ""
try:
d = dt.datetime.fromisoformat(str(value).replace("Z", "+00:00"))
except ValueError:
return str(value)
if d.tzinfo is None:
d = d.replace(tzinfo=dt.timezone.utc)
d = d.astimezone(services.tz())
return f"{d.strftime('%B')} {d.day}, {d.year} {d.strftime('%H:%M')} {d.tzname() or ''}".strip()
def short_ref(value) -> str:
"""Short reference shown to submitters and admins (first 8 hex digits of the id)."""
return str(value or "")[:8].upper()
async def read_form(request: Request) -> FormData:
"""Read and parse a form body once, before the handler runs in the thread pool.
Only ordinary URL-encoded forms are accepted (the site never uploads files),
the body is capped while it streams (so chunked requests cannot skip the
Content-Length check in the middleware), and only text values are kept.
"""
content_type = request.headers.get("content-type", "").split(";")[0].strip().lower()
if content_type not in ("application/x-www-form-urlencoded", ""):
raise HTTPException(415, "This form must be sent as an ordinary web form.")
body = bytearray()
async for chunk in request.stream():
body += chunk
if len(body) > MAX_BODY_BYTES:
raise HTTPException(413, "The request is too large.")
if not body:
return FormData()
if content_type == "":
raise HTTPException(415, "This form must be sent as an ordinary web form.")
request._body = bytes(body)
form = await request.form()
return FormData([(k, v) for k, v in form.multi_items() if isinstance(v, str)])
def create_app(settings: Optional[Settings] = None, db: Optional[Db] = None) -> FastAPI:
settings = settings or get_settings()
app = FastAPI(title=APP_TITLE, docs_url=None, redoc_url=None, openapi_url=None)
app.mount("/static", StaticFiles(directory=str(BASE_DIR / "static")), name="static")
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(str(BASE_DIR / "templates")),
autoescape=True, undefined=jinja2.StrictUndefined,
extensions=["jinja2.ext.do"])
templates = Jinja2Templates(env=jinja_env)
sessions = SessionManager(settings.session_secret, settings.session_hours * 3600)
form_tokens = FormTokens(settings.session_secret)
limiter = RateLimiter()
if db is None and settings.db_configured:
db = Db(settings.supabase_url, settings.supabase_key, settings.supabase_rest_path)
state = {"db": db}
# -- small in-memory cache of published listings ----------------------
cache = {"rows": None, "at": 0.0, "gen": 0}
cache_lock = threading.Lock()
def get_db() -> Db:
if state["db"] is None:
raise HTTPException(503, "The database is not configured. Set SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY.")
return state["db"]
def published_listings() -> list[dict]:
with cache_lock:
if cache["rows"] is not None and time.monotonic() - cache["at"] < settings.cache_seconds:
return cache["rows"]
gen = cache["gen"]
rows = get_db().select("listings", {"status": "eq.published"}, order="updated_on.desc,faculty_name.asc")
with cache_lock:
if cache["gen"] == gen: # nothing changed while we were reading
cache["rows"], cache["at"] = rows, time.monotonic()
return rows
def invalidate_cache() -> None:
with cache_lock:
cache["rows"], cache["at"] = None, 0.0
cache["gen"] += 1
app.state.invalidate_cache = invalidate_cache
def published_listing(listing_id: str) -> Optional[dict]:
"""Fresh lookup (not the cache) of a listing that must be published."""
try:
lid = check_uuid(listing_id)
except ValueError:
return None
row = get_db().get_one("listings", lid)
return row if row and row.get("status") == "published" else None
# -- template helpers ----------------------------------------------------
templates.env.filters["fmt_date"] = fmt_date
templates.env.filters["fmt_datetime"] = fmt_datetime
templates.env.filters["safe_href"] = services.safe_href
templates.env.filters["split_list"] = split_list
templates.env.filters["short_ref"] = short_ref
templates.env.globals.update({
"APP_TITLE": APP_TITLE,
"CONTACT_EMAIL": CONTACT_EMAIL,
"CONTENT_FIELDS": CONTENT_FIELDS,
"FIELDS_BY_KEY": FIELDS_BY_KEY,
"SUBMITTER_FIELDS": SUBMITTER_FIELDS,
"SUMMARY_KEYS": SUMMARY_KEYS,
"ELIGIBILITY_NOTE": ELIGIBILITY_NOTE,
"split_known": split_known,
"area_color": area_color,
})
def render(request: Request, name: str, ctx: dict, status_code: int = 200) -> HTMLResponse:
ctx = dict(ctx)
ctx.setdefault("admin", bool(current_session(request)))
ctx.setdefault("nav", "")
ctx.setdefault("flash", FLASH.get(request.query_params.get("msg", ""), ""))
return templates.TemplateResponse(request, name, ctx, status_code=status_code)
# -- security plumbing --------------------------------------------------
def current_session(request: Request) -> Optional[dict]:
return sessions.read(request.cookies.get(SESSION_COOKIE))
def require_admin(request: Request) -> dict:
sess = current_session(request)
if not sess:
nxt = request.url.path if request.method == "GET" else "/admin"
raise HTTPException(status_code=303, headers={"Location": "/admin/login?" + urlencode({"next": nxt})})
return sess
def check_csrf(sess: dict, form: FormData) -> None:
token = form.get("csrf_token")
if not token or token != sess.get("csrf"):
raise HTTPException(400, "The form token is missing or expired. Go back, reload the page and try again.")
def set_session_cookie(resp: Response, value: str) -> None:
resp.set_cookie(SESSION_COOKIE, value, max_age=sessions.max_age, httponly=True, samesite="lax",
secure=settings.cookie_secure, path="/")
def _safe_next(value: Optional[str], default: str = "/admin") -> str:
"""Only allow redirects to admin pages on this site."""
v = (value or "").strip()
return v if v.startswith("/admin") and "//" not in v and "\\" not in v else default
def request_ip(request: Request) -> str:
return client_ip(request.headers, request.client.host if request.client else "")
@app.middleware("http")
async def guard_and_headers(request: Request, call_next):
length = request.headers.get("content-length", "")
if length.isdigit() and int(length) > MAX_BODY_BYTES:
return render(request, "error.html", {"status": 413, "detail": "The request is too large."}, 413)
resp = await call_next(request)
resp.headers["Content-Security-Policy"] = (
"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; "
"form-action 'self'; base-uri 'self'; object-src 'none'; "
"frame-ancestors 'self' https://huggingface.co https://*.hf.space"
)
resp.headers["X-Content-Type-Options"] = "nosniff"
resp.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
if request.url.path.startswith("/admin"):
resp.headers["Cache-Control"] = "no-store"
return resp
@app.exception_handler(StarletteHTTPException)
async def http_error(request: Request, exc: StarletteHTTPException):
if exc.status_code == 303 and exc.headers and "Location" in exc.headers:
return RedirectResponse(exc.headers["Location"], status_code=303)
detail = exc.detail if isinstance(exc.detail, str) else "Request could not be completed."
if exc.status_code == 404 and detail == "Not Found":
detail = "There is no page at this address."
elif exc.status_code == 405:
detail = "This address does not accept that kind of request."
return render(request, "error.html", {"status": exc.status_code, "detail": detail},
status_code=exc.status_code)
@app.exception_handler(DbError)
async def db_error(request: Request, exc: DbError):
log.error("database failure on %s: %s", request.url.path, exc)
return render(request, "error.html",
{"status": 503, "detail": "The database is temporarily unavailable. Please try again in a moment."},
status_code=503)
# ======================================================================
# Public pages
# ======================================================================
@app.get("/healthz")
def healthz():
return {"ok": True, "db_configured": state["db"] is not None, "admin_configured": settings.admin_enabled}
@app.get("/", response_class=HTMLResponse)
def index(request: Request):
p = request.query_params
q = (p.get("q") or "").strip()[:200]
type_, term, standing = (p.get(k, "").strip()[:100] for k in ("type", "term", "standing"))
rows = published_listings()
options = services.filter_options(rows)
# Several areas may be chosen; only known areas are accepted.
areas = [a for a in dict.fromkeys(v.strip() for v in p.getlist("area")) if a in options["areas"]]
sort = p.get("sort", "updated")
if sort not in ("updated", "faculty"):
sort = "updated"
shown = services.sort_listings(
services.filter_listings(rows, q=q, areas=areas, type_=type_, term=term, standing=standing), sort)
active = {"q": q, "areas": areas, "type": type_, "term": term, "standing": standing, "sort": sort}
return render(request, "index.html", {
"listings": shown, "total": len(rows), "options": options, "f": active,
"filtered": any([q, areas, type_, term, standing]),
})
@app.get("/listings/{listing_id}", response_class=HTMLResponse)
def listing_detail(request: Request, listing_id: str):
try:
lid = check_uuid(listing_id)
except ValueError:
raise HTTPException(404, "Listing not found.")
row = next((r for r in published_listings() if r["id"] == lid), None)
if row is None:
raise HTTPException(404, "Listing not found.")
return render(request, "listing.html", {"l": row})
def _listing_choices() -> list[dict]:
"""Faculty names for the 'update an existing listing' picker; when one
name has several listings, the keywords tell them apart."""
rows = services.sort_listings(published_listings(), "faculty")
names = [str(r.get("faculty_name") or "") for r in rows]
out = []
for r in rows:
label = str(r.get("faculty_name") or "")
if names.count(label) > 1:
detail = str(r.get("keywords") or "")[:60] or f"updated {fmt_date(r.get('updated_on'))}"
label = f"{label} ({detail})"
out.append({"id": r["id"], "label": label})
return out
def _with_choice_state(content: dict, form: FormData) -> dict:
"""Values for re-rendering a form: what was typed, including which
boxes were ticked and the 'other' text."""
values = dict(content)
for f in CONTENT_FIELDS:
if f.kind == "choices":
values[f.key + "__selected"] = [s for s in form.getlist(f.key) if s in f.choices]
values[f.key + "__other"] = form.get(f.key + "_other") or ""
return values
def render_submit(request: Request, values: dict, errors: dict, update_of: Optional[dict], status: int = 200):
return render(request, "submit.html", {
"values": values, "errors": errors, "update_of": update_of, "form_token": form_tokens.issue(),
"listings_for_update": _listing_choices() if not update_of else [],
}, status)
@app.get("/submit", response_class=HTMLResponse)
def submit_form(request: Request):
update_of = None
values: dict = {"application_deadline": "Rolling"}
wanted = request.query_params.get("listing", "").strip()
if wanted:
update_of = published_listing(wanted)
if update_of is None:
raise HTTPException(404, "Listing not found.")
values = services.content_of(update_of)
return render_submit(request, values, {}, update_of)
@app.post("/submit", response_class=HTMLResponse)
def submit_post(request: Request, form: FormData = Depends(read_form)):
ip = request_ip(request)
if (form.get("website") or "").strip():
# Honeypot field filled in: almost certainly an automated submission.
log.warning("honeypot triggered from %s", ip)
raise HTTPException(400, "Submission rejected.")
who, who_errors = services.validate_submitter(form)
errors: dict = {}
update_of = None
listing_id = (form.get("listing_id") or "").strip()
if listing_id:
update_of = published_listing(listing_id)
if update_of is None:
errors["listing"] = ("The listing you were updating is no longer available, so this will be "
"submitted as a new listing. Check the details below and submit again.")
content, content_errors = services.validate_content(form, existing=update_of)
errors.update(content_errors)
errors.update(who_errors)
if not form_tokens.verify(form.get("form_token")):
errors["form_token"] = TOKEN_MESSAGE
if errors:
values = _with_choice_state(content, form)
values.update({k: form.get(k) for k in ("submitter_name", "submitter_netid", "submitter_email")})
return render_submit(request, values, errors, update_of, 400 if "form_token" in errors else 422)
if limiter.is_limited("submit", ip, *SUBMIT_LIMIT) or limiter.is_limited("submit", "*", *SUBMIT_GLOBAL_LIMIT):
errors["form_token"] = ("Too many submissions have been sent from this network in the last hour, so "
"this one was not sent. Your entries are still here; please try again later.")
values = _with_choice_state(content, form)
values.update({k: form.get(k) for k in ("submitter_name", "submitter_netid", "submitter_email")})
return render_submit(request, values, errors, update_of, 429)
row = dict(content)
row.update(who)
row["kind"] = "update" if update_of else "new"
row["listing_id"] = update_of["id"] if update_of else None
row["status"] = "pending"
created = get_db().insert("submissions", row)
limiter.hit("submit", ip, *SUBMIT_LIMIT)
limiter.hit("submit", "*", *SUBMIT_GLOBAL_LIMIT)
return RedirectResponse(
f"/submit/thanks?{urlencode({'ref': short_ref(created['id']), 'kind': row['kind']})}", status_code=303)
@app.get("/submit/thanks", response_class=HTMLResponse)
def submit_thanks(request: Request):
ref = request.query_params.get("ref", "")[:8]
kind = request.query_params.get("kind", "new")
return render(request, "submit_done.html", {"ref": ref, "kind": kind})
# ======================================================================
# Admin
# ======================================================================
@app.get("/admin/login", response_class=HTMLResponse)
def login_form(request: Request):
if current_session(request):
return RedirectResponse("/admin", status_code=303)
return render(request, "admin_login.html", {"error": "", "enabled": settings.admin_enabled,
"next": _safe_next(request.query_params.get("next"))})
@app.post("/admin/login", response_class=HTMLResponse)
def login_post(request: Request, form: FormData = Depends(read_form)):
ip = request_ip(request)
nxt = _safe_next(form.get("next"))
if not settings.admin_enabled:
return render(request, "admin_login.html", {"error": "Admin sign-in is not configured.", "enabled": False, "next": nxt}, 503)
if limiter.is_limited("login", ip, *LOGIN_LIMIT):
return render(request, "admin_login.html",
{"error": "Too many failed attempts. Wait 15 minutes and try again.", "enabled": True, "next": nxt}, 429)
if not password_matches(settings.admin_password, form.get("password") or ""):
limiter.hit("login", ip, *LOGIN_LIMIT)
log.warning("failed admin sign-in from %s", ip)
return render(request, "admin_login.html", {"error": "Incorrect password.", "enabled": True, "next": nxt}, 401)
limiter.reset("login", ip)
cookie_value, _ = sessions.create()
resp = RedirectResponse(nxt, status_code=303)
set_session_cookie(resp, cookie_value)
return resp
@app.post("/admin/logout")
def logout(request: Request, form: FormData = Depends(read_form)):
sess = current_session(request)
if sess:
check_csrf(sess, form)
elif SESSION_COOKIE not in request.cookies:
# A cross-site post without our cookie must not be able to sign anyone out.
return RedirectResponse("/admin/login", status_code=303)
resp = RedirectResponse("/admin/login?msg=signed_out", status_code=303)
resp.delete_cookie(SESSION_COOKIE, path="/")
return resp
@app.get("/admin", response_class=HTMLResponse)
def admin_home(request: Request):
sess = require_admin(request)
db = get_db()
pending = db.select("submissions", {"status": "eq.pending"}, order="created_at.asc")
unfinished = db.select("submissions", {"status": "eq.approved", "published_at": "is.null"}, order="created_at.asc")
counts = {
"pending": len(pending),
"unfinished": len(unfinished),
"published": db.count("listings", {"status": "eq.published"}),
"retired": db.count("listings", {"status": "eq.retired"}),
}
return render(request, "admin_home.html", {"pending": pending, "unfinished": unfinished, "counts": counts, "csrf": sess["csrf"]})
@app.get("/admin/submissions", response_class=HTMLResponse)
def admin_submissions(request: Request):
sess = require_admin(request)
status = request.query_params.get("status", "approved")
if status not in ("approved", "rejected", "pending"):
status = "approved"
rows = get_db().select("submissions", {"status": f"eq.{status}"}, order="created_at.desc", limit=200)
return render(request, "admin_submissions.html", {"rows": rows, "status": status, "csrf": sess["csrf"]})
def _load_submission(submission_id: str) -> dict:
try:
sub = get_db().get_one("submissions", submission_id)
except ValueError:
sub = None
if not sub:
raise HTTPException(404, "Submission not found.")
return sub
@app.get("/admin/submissions/{submission_id}", response_class=HTMLResponse)
def admin_submission(request: Request, submission_id: str):
sess = require_admin(request)
sub = _load_submission(submission_id)
current = get_db().get_one("listings", sub["listing_id"]) if sub.get("listing_id") else None
same_faculty = []
if sub.get("kind") == "new" and sub.get("faculty_name"):
wanted = sub["faculty_name"].strip().lower()
same_faculty = [r for r in published_listings() if (r.get("faculty_name") or "").strip().lower() == wanted]
return render(request, "admin_submission.html", {
"s": sub, "current": current, "diff": services.diff_fields(current, sub), "csrf": sess["csrf"],
"same_faculty": same_faculty, "unfinished": services.is_unfinished(sub),
})
@app.post("/admin/submissions/{submission_id}/approve")
def admin_approve(request: Request, submission_id: str, form: FormData = Depends(read_form)):
sess = require_admin(request)
check_csrf(sess, form)
try:
listing = services.approve_submission(get_db(), submission_id)
except services.ApprovalError as exc:
raise HTTPException(409, str(exc))
except (LookupError, ValueError):
raise HTTPException(404, "Submission not found.")
invalidate_cache()
msg = "approved" if listing.get("status") == "published" else "approved_retired"
return RedirectResponse(f"/admin/listings/{listing['id']}/edit?msg={msg}", status_code=303)
@app.post("/admin/submissions/{submission_id}/reject")
def admin_reject(request: Request, submission_id: str, form: FormData = Depends(read_form)):
sess = require_admin(request)
check_csrf(sess, form)
try:
services.reject_submission(get_db(), submission_id, form.get("admin_note"))
except services.ApprovalError as exc:
raise HTTPException(409, str(exc))
except (LookupError, ValueError):
raise HTTPException(404, "Submission not found.")
invalidate_cache()
return RedirectResponse("/admin?msg=rejected", status_code=303)
@app.get("/admin/listings", response_class=HTMLResponse)
def admin_listings(request: Request):
sess = require_admin(request)
status = request.query_params.get("status", "published")
if status not in ("published", "retired"):
status = "published"
q = (request.query_params.get("q") or "").strip()[:200]
rows = get_db().select("listings", {"status": f"eq.{status}"}, order="faculty_name.asc")
if q:
rows = services.filter_listings(rows, q=q)
rows = services.sort_listings(rows, "faculty")
return render(request, "admin_listings.html", {"rows": rows, "status": status, "q": q, "csrf": sess["csrf"]})
def _edit_context(sess: dict, listing: Optional[dict], values: dict, errors: dict, bump: bool = True) -> dict:
return {"l": listing, "values": values, "errors": errors, "csrf": sess["csrf"], "bump": bump}
@app.get("/admin/listings/new", response_class=HTMLResponse)
def admin_listing_new(request: Request):
sess = require_admin(request)
return render(request, "admin_listing_form.html",
_edit_context(sess, None, {"application_deadline": "Rolling"}, {}))
@app.post("/admin/listings/new")
def admin_listing_create(request: Request, form: FormData = Depends(read_form)):
sess = require_admin(request)
check_csrf(sess, form)
content, errors = services.validate_content(form)
if errors:
return render(request, "admin_listing_form.html",
_edit_context(sess, None, _with_choice_state(content, form), errors), 422)
row = dict(content)
row.update({"status": "published", "source": "admin", "updated_on": services.today().isoformat()})
listing = get_db().insert("listings", row)
invalidate_cache()
return RedirectResponse(f"/admin/listings/{listing['id']}/edit?msg=created", status_code=303)
def _load_listing(listing_id: str) -> dict:
try:
listing = get_db().get_one("listings", listing_id)
except ValueError:
listing = None
if not listing:
raise HTTPException(404, "Listing not found.")
return listing
@app.get("/admin/listings/{listing_id}/edit", response_class=HTMLResponse)
def admin_listing_edit(request: Request, listing_id: str):
sess = require_admin(request)
listing = _load_listing(listing_id)
return render(request, "admin_listing_form.html",
_edit_context(sess, listing, services.content_of(listing), {}))
@app.post("/admin/listings/{listing_id}/edit")
def admin_listing_save(request: Request, listing_id: str, form: FormData = Depends(read_form)):
sess = require_admin(request)
check_csrf(sess, form)
listing = _load_listing(listing_id)
content, errors = services.validate_content(form, existing=listing)
if errors:
return render(request, "admin_listing_form.html",
_edit_context(sess, listing, _with_choice_state(content, form), errors,
bump=form.get("bump_updated") == "1"), 422)
patch = dict(content)
if form.get("bump_updated") == "1":
patch["updated_on"] = services.today().isoformat()
get_db().update("listings", {"id": f"eq.{listing['id']}"}, patch)
invalidate_cache()
return RedirectResponse(f"/admin/listings/{listing['id']}/edit?msg=saved", status_code=303)
def _set_status(request: Request, listing_id: str, form: FormData, status: str, msg: str):
sess = require_admin(request)
check_csrf(sess, form)
try:
lid = check_uuid(listing_id)
except ValueError:
raise HTTPException(404, "Listing not found.")
patch = {"status": status,
"retired_at": dt.datetime.now(dt.timezone.utc).isoformat() if status == "retired" else None}
rows = get_db().update("listings", {"id": f"eq.{lid}"}, patch)
if not rows:
raise HTTPException(404, "Listing not found.")
invalidate_cache()
back = _safe_next(form.get("next"), default="/admin/listings")
sep = "&" if "?" in back else "?"
return RedirectResponse(f"{back}{sep}msg={msg}", status_code=303)
@app.post("/admin/listings/{listing_id}/retire")
def admin_listing_retire(request: Request, listing_id: str, form: FormData = Depends(read_form)):
return _set_status(request, listing_id, form, "retired", "retired")
@app.post("/admin/listings/{listing_id}/restore")
def admin_listing_restore(request: Request, listing_id: str, form: FormData = Depends(read_form)):
return _set_status(request, listing_id, form, "published", "restored")
@app.get("/admin/export.csv")
def admin_export(request: Request):
require_admin(request)
rows = get_db().select("listings", order="status.asc,faculty_name.asc")
buf = io.StringIO()
buf.write("") # BOM so Excel opens UTF-8 correctly
w = csv.writer(buf)
headers = ["id", "status", "updated_on"] + FIELD_KEYS + ["source", "created_at", "updated_at"]
w.writerow([FIELDS_BY_KEY[h].label if h in FIELDS_BY_KEY else h for h in headers])
for r in rows:
w.writerow([_csv_cell(r.get(h)) for h in headers])
stamp = services.today().isoformat()
return StreamingResponse(iter([buf.getvalue()]), media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": f'attachment; filename="curas-listings-{stamp}.csv"'})
return app
def _csv_cell(value) -> str:
"""Stop spreadsheet programs from treating a cell as a formula."""
if value is None:
return ""
s = str(value)
return " " + s if s[:1] in ("=", "+", "-", "@", "\t", "\r") else s
app = create_app()