Archived
32 lines
1.0 KiB
Python
32 lines
1.0 KiB
Python
from __future__ import annotations
|
|
|
|
import urllib.parse
|
|
|
|
from fastapi import HTTPException, Request
|
|
|
|
from ..ddns_models import DdnsSettings
|
|
|
|
MAX_FORM_FIELDS = 100
|
|
|
|
|
|
def parse_form(body: bytes) -> dict[str, list[str]]:
|
|
try:
|
|
decoded = body.decode("utf-8")
|
|
except UnicodeDecodeError as exc:
|
|
raise HTTPException(status_code=400, detail="form body must be valid UTF-8") from exc
|
|
try:
|
|
return urllib.parse.parse_qs(decoded, keep_blank_values=True, max_num_fields=MAX_FORM_FIELDS)
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=f"form must not contain more than {MAX_FORM_FIELDS} fields") from exc
|
|
|
|
|
|
async def request_form(request: Request, settings: DdnsSettings) -> dict[str, list[str]]:
|
|
body = await request.body()
|
|
if len(body) > settings.max_request_body_bytes:
|
|
raise HTTPException(status_code=413, detail="request body too large")
|
|
return parse_form(body)
|
|
|
|
|
|
def first_form_value(form: dict[str, list[str]], key: str) -> str:
|
|
return form.get(key, [""])[0].strip()
|