Fixed up Pylance issues WITHOUT destroying half the functionality we just did.

This commit is contained in:
Yaro Kasear 2025-08-15 15:00:07 -05:00
parent 4e15972275
commit 247b167377
3 changed files with 89 additions and 54 deletions

View file

@ -1,5 +1,7 @@
from flask import Blueprint, request, render_template, jsonify, abort
from sqlalchemy.engine import ScalarResult
from sqlalchemy.exc import IntegrityError
from sqlalchemy.sql import Select
from typing import Any, Optional, List, cast, Type, Iterable
from .defaults import (
@ -45,21 +47,49 @@ def call(Model: type, name: str, *args: Any, **kwargs: Any) -> Any:
def list_items(model_name):
Model = get_model_class(model_name)
text = (request.args.get("q") or "").strip() or None
limit_param = request.args.get("limit")
limit: int | None = None if limit_param in (None, "", "0", "-1") else min(int(limit_param), 500)
# 0 / -1 / blank => unlimited (pass 0)
if limit_param in (None, "", "0", "-1"):
effective_limit = 0
else:
effective_limit = min(int(limit_param), 500)
offset = int(request.args.get("offset", 0))
view = (request.args.get("view") or "json").strip()
# Build kwargs so we only include 'limit' when it's an int
qkwargs: dict[str, Any] = {"text": text, "offset": offset}
if limit is not None:
qkwargs["limit"] = limit
sort = (request.args.get("sort") or "").strip() or None
direction = (request.args.get("dir") or request.args.get("direction") or "asc").lower()
if direction not in ("asc", "desc"):
direction = "asc"
rows_iter: Iterable[Any] = (
call(Model, "ui_query", db.session, **qkwargs)
or default_query(db.session, Model, **qkwargs)
)
rows = list(rows_iter)
qkwargs: dict[str, Any] = {
"text": text,
"limit": effective_limit,
"offset": offset,
"sort": sort,
"direction": direction,
}
# Prefer per-model override. Contract: return list[Model] OR a Select (SA 2.x).
rows_any: Any = call(Model, "ui_query", db.session, **qkwargs)
if rows_any is None:
rows = default_query(db.session, Model, **qkwargs)
elif isinstance(rows_any, list):
rows = rows_any
elif isinstance(rows_any, Select):
rows = list(cast(ScalarResult[Any], db.session.execute(rows_any).scalars()))
else:
# If someone returns a Result or other iterable of models
try:
# Try SQLAlchemy Result-like
scalars = getattr(rows_any, "scalars", None)
if callable(scalars):
rows = list(cast(ScalarResult[Any], scalars()))
else:
rows = list(rows_any)
except TypeError:
rows = [rows_any]
items = [
(call(Model, "ui_serialize", r, view=view) or default_serialize(Model, r, view=view))