id_list.py 1016 B

1234567891011121314151617181920212223242526272829
  1. """Comma-separated id lists for the bulk endpoints that serve page-wide requests."""
  2. from fastapi import HTTPException
  3. # Enough for any farm's Printers page in one request; the frontend batcher
  4. # splits anything longer.
  5. MAX_IDS = 500
  6. def parse_id_list(value: str) -> list[int]:
  7. """Parse ``"3,1,3"`` into ``[3, 1]``: ids in first-seen order, duplicates dropped.
  8. Raises 422 on anything that isn't a positive integer, or more than
  9. ``MAX_IDS`` ids.
  10. """
  11. ids: list[int] = []
  12. for part in value.split(","):
  13. part = part.strip()
  14. if not part:
  15. continue
  16. # isdigit() alone also passes "²" (which int() then rejects) and other
  17. # scripts' digits
  18. if not (part.isascii() and part.isdigit()) or int(part) <= 0:
  19. raise HTTPException(422, f"Invalid id: {part!r}")
  20. if int(part) not in ids:
  21. ids.append(int(part))
  22. if len(ids) > MAX_IDS:
  23. raise HTTPException(422, f"At most {MAX_IDS} ids per request")
  24. return ids