Coverage for fastapi_restly/views/_base.py: 98%

622 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-09 21:47 +0000

1""" 

2This module provides a framework for class-based views on SQLAlchemy models. 

3 

4View class: 

5This class is used to create a collection of endpoints that share an 

6APIRouter (created when calling `include_view()`) and dependencies 

7as class attributes. It uses the same mechanics as the class based 

8view decorator from fastapi-utils. 

9(https://fastapi-utils.davidmontague.xyz/user-guide/class-based-views/) 

10 

11AsyncRestView: 

12Provides default reading and writing functions on the database using 

13SQLAlchemy models. 

14""" 

15 

16import collections.abc 

17import dataclasses 

18import functools 

19import inspect 

20import itertools 

21import types 

22import warnings 

23from collections.abc import Iterable, Mapping 

24from enum import Enum 

25from typing import ( 

26 TYPE_CHECKING, 

27 Annotated, 

28 Any, 

29 Callable, 

30 ClassVar, 

31 Generic, 

32 Iterable, 

33 Literal, 

34 Sequence, 

35 cast, 

36 final, 

37 get_args, 

38 get_origin, 

39) 

40 

41import fastapi 

42import pydantic 

43from fastapi.utils import is_body_allowed_for_status_code 

44from sqlalchemy import Boolean, ColumnElement, Select 

45from sqlalchemy import inspect as sa_inspect 

46from sqlalchemy import select as sa_select 

47from starlette.datastructures import QueryParams 

48from typing_extensions import TypeVar 

49 

50from ..clauses import WhereClause, all_of, apply_clauses 

51 

52#: A per-read scope: ``None`` for the view's own, a clause that replaces it 

53#: for that read, or ``fr.clauses.UNSCOPED``. 

54ReadScope = WhereClause | None 

55 

56# A per-read narrowing filter: a SQLAlchemy boolean expression, or anything 

57# all_of takes. Private: only the final list handler accepts one, so no 

58# override spells it. 

59_ReadWhere = ColumnElement[bool] | WhereClause | None 

60from .._mapping import is_mapped_class 

61from .._pagination import ( 

62 _DEFAULT_PAGINATION, 

63 Pagination, 

64 _build_envelope, 

65 _check_fillable, 

66 _query_settings, 

67 _settings_of, 

68) 

69from ..exc import NotFound, RestlyConfigurationError, RestlySkippedFilterMethodsWarning 

70from ..objects import snapshot as _object_snapshot 

71from ..query._impl import _list_params_values, _OwnFilter, _record_of 

72from ..query._paged import ( 

73 _PAGINATION_OF_BASE, 

74 _page_fields_base, 

75 _redeclared_page_fields, 

76 _takes_page_fields, 

77) 

78from ..query._shared import SortNulls 

79from ..schemas import BaseSchema 

80from ..schemas._base import ( 

81 _as_response, 

82 _reject_table_class, 

83 _reject_table_subclass, 

84 _reject_writable_table_class, 

85 _response_adapter, 

86 _schema_resource_name, 

87) 

88from ._generated import ( 

89 _DEFAULT_SETTINGS, 

90 _drop_stale_settings, 

91 _list_params_schema, 

92 _uses_default, 

93) 

94from ._guards import ( 

95 _FINAL_HANDLERS, 

96 _FINAL_LOADS, 

97 _REMOVED_DOMAIN_UTILITIES, 

98 _check_atomic_write_actions, 

99 _check_list_settings, 

100 _check_load_hooks, 

101 _check_pagination_setting, 

102 _check_renamed_names, 

103 _check_unknown_query_params, 

104 _final_handler_message, 

105 _missing_view_attribute, 

106 _origin, 

107 _owner, 

108 _reject_bare_verb_route_names, 

109 _reject_route_names_of_settings, 

110 _route_parameters, 

111 _set_by, 

112) 

113from ._list_params import ( 

114 _LIST_SETTING_DEFAULTS, 

115 _how_set, 

116 _list_filter_methods, 

117 _list_params_dependency, 

118 _list_params_fields, 

119 _list_setting, 

120 _validate_raw_list_params, 

121 reject_unknown_query_keys, 

122) 

123from ._reads import ( 

124 _build_relationship_loader_options, 

125 _check_identity_tables, 

126 _checked_scope, 

127 _checked_where, 

128 _clause_element, 

129 _model_scope, 

130 _not_found_message, 

131 _primary_key_criterion, 

132 _reject_bad_row_identity, 

133 _rows_reload_statements, 

134) 

135from ._schema_types import ( 

136 SchemaType, 

137 _bare, 

138 _fill_schema_types, 

139 _schema_type_in, 

140 _without_none, 

141) 

142 

143# Unbound: a mapped class need not subclass DeclarativeBase (a SQLModel table, 

144# an imperative mapping). ``BaseRestView`` checks the mapping at class definition. 

145ModelT = TypeVar("ModelT", default=Any) 

146ResponseSchemaT = TypeVar( 

147 "ResponseSchemaT", bound=pydantic.BaseModel, default=BaseSchema 

148) 

149CreateSchemaT = TypeVar( 

150 "CreateSchemaT", bound=pydantic.BaseModel, default=pydantic.BaseModel 

151) 

152UpdateSchemaT = TypeVar( 

153 "UpdateSchemaT", bound=pydantic.BaseModel, default=pydantic.BaseModel 

154) 

155IdT = TypeVar("IdT", default=int) 

156 

157 

158@dataclasses.dataclass(frozen=True) 

159class ListResult(Generic[ModelT]): 

160 """Result returned by ``get_many`` before HTTP response formatting. 

161 

162 ``total_count`` is ``None`` for a list without pagination, which does not 

163 run the count query. ``list_params`` holds the list params that 

164 ``get_many`` received, so :meth:`BaseRestView.to_list_response` can read 

165 the page from them. 

166 """ 

167 

168 #: The rows that the list loaded: one page, or every row for a list 

169 #: without pagination. 

170 objects: Sequence[ModelT] 

171 #: The number of rows that match the filters, on all pages. It is 

172 #: ``None`` for a list without pagination. A paginated list response 

173 #: sends ``None`` as ``0``. 

174 total_count: int | None = None 

175 #: The list params that ``get_many`` received. Pass on the list params 

176 #: that you received: :meth:`BaseRestView.to_list_response` reads the 

177 #: values of the page from them, and without them it reports the first 

178 #: page on every page. 

179 list_params: Any = None 

180 

181 

182class Action: 

183 """The names of the five CRUD actions: the ``action`` that ``authorize`` 

184 gets. A write, such as ``CREATE`` or the action of a ``write_action`` 

185 block, also passes it to ``before_action_commit`` and 

186 ``after_action_commit``. A read, ``GET_MANY`` or ``GET_ONE``, has no 

187 commit, so it reaches only ``authorize``. 

188 

189 Each view has a class ``Action`` that lists all its actions. It is this 

190 class, until a view adds actions of its own in a subclass:: 

191 

192 class PostView(fr.AsyncRestView): 

193 class Action(fr.Action): 

194 PUBLISH = "publish" 

195 

196 An ``Action`` class has only actions. An action has an UPPER_CASE name, 

197 and its value is that name in lower case. ``write_action`` takes only a 

198 value that the view's ``Action`` declares. A view with base classes that 

199 declare actions, such as a mixin, inherits from their ``Action`` classes 

200 too. 

201 """ 

202 

203 #: Read a list, as ``GET /`` does. A read has no commit. 

204 GET_MANY = "get_many" 

205 #: Read one row, as ``GET /{id}`` does. A read has no commit. 

206 GET_ONE = "get_one" 

207 #: Create a row, as ``POST /`` does. 

208 CREATE = "create" 

209 #: Update a row, as ``PATCH /{id}`` does. 

210 UPDATE = "update" 

211 #: Delete a row, as ``DELETE /{id}`` does. 

212 DELETE = "delete" 

213 

214 def __init_subclass__(cls, **kwargs: Any) -> None: 

215 super().__init_subclass__(**kwargs) 

216 for key in dir(cls): 

217 if key.startswith("_"): 

218 continue 

219 if not key.isupper(): 

220 raise RestlyConfigurationError( 

221 f"{cls.__qualname__}.{key}: an Action class has only " 

222 "actions, and an action has an UPPER_CASE name, such as " 

223 "PUBLISH = 'publish'." 

224 ) 

225 value = getattr(cls, key) 

226 if value != key.lower(): 

227 raise RestlyConfigurationError( 

228 f"{cls.__qualname__}.{key} is {value!r}. The value of an " 

229 f"action is its name in lower case: {key} = {key.lower()!r}." 

230 ) 

231 

232 

233def _declares(action_class: type, action: object) -> bool: 

234 """Whether ``action_class`` declares ``action``, such as ``"publish"``.""" 

235 return ( 

236 isinstance(action, str) 

237 and getattr(action_class, action.upper(), None) == action 

238 ) 

239 

240 

241class View: 

242 """ 

243 Class-based view primitive for FastAPI. 

244 

245 Group related endpoints on a class, share dependencies and metadata via 

246 class attributes, and let subclasses override individual route methods. 

247 Routes are bound at :func:`include_view` time, not at class-definition 

248 time, so subclassing works the way Python developers expect: override a 

249 method on a subclass and the override is what runs. 

250 

251 Most users will subclass :class:`RestView` or :class:`AsyncRestView`, 

252 which extend ``View`` with CRUD scaffolding. Use ``View`` directly for 

253 grouped non-CRUD endpoints (auth flows, custom RPC routes, etc.). 

254 """ 

255 

256 #: The URL prefix of every route. Each class in the hierarchy that sets one 

257 #: adds a segment, base first. Without a prefix, the routes are at the root. 

258 prefix: ClassVar[str] 

259 #: The OpenAPI tags of every route. When it is not set, the tag is the 

260 #: last part of the prefix in title case, so ``/order-items`` gives 

261 #: ``Order Items``. Without a prefix, the tag is the class name. On a 

262 #: router with tags of its own, Restly makes no tag: the routes get the 

263 #: tags of the router, as a plain route on it does. Setting it replaces 

264 #: the tag that Restly makes. 

265 tags: ClassVar[Iterable[str | Enum] | None] = None 

266 #: FastAPI dependencies run for every route, without injecting a result. 

267 #: Each class in the hierarchy adds its own, base first, so a subclass 

268 #: cannot drop a base's guard. A subclass that lists a base's entry again 

269 #: runs it where it lists it. 

270 dependencies: ClassVar[Any] = None 

271 #: OpenAPI responses documented on every route. Each class in the hierarchy 

272 #: adds its own, and a subclass's entry for a status code wins. A status set 

273 #: to ``None`` is left out, so ``{404: None}`` removes the 404 that a CRUD 

274 #: view documents on a route that can answer 404. 

275 responses: ClassVar[dict[int | str, dict[str, Any] | None]] = {} 

276 

277 if TYPE_CHECKING: 

278 # include_view replaces __init__: each injected attribute becomes a 

279 # keyword, so code that builds a view by hand passes them by name. 

280 def __init__(self, **dependencies: Any) -> None: ... 

281 

282 def __init_subclass__(cls, **kwargs: Any) -> None: 

283 super().__init_subclass__(**kwargs) 

284 _apply_modified_routes(cls) 

285 _reject_route_names_of_settings(cls) 

286 

287 @classmethod 

288 def before_include_view(cls) -> None: 

289 """Run by :func:`include_view` once per class, before its routes are 

290 registered. A no-op here; override to adjust route methods first.""" 

291 

292 

293def route(path: str, **api_route_kwargs: Any) -> Callable[..., Any]: 

294 """Mark a view method as an endpoint, with the HTTP method and the route 

295 options that you pass. 

296 

297 ``path`` and ``api_route_kwargs`` go to FastAPI's 

298 ``APIRouter.add_api_route()`` when :func:`include_view` registers the 

299 view. Without ``methods=``, the route is a ``GET`` with status 200, as in 

300 FastAPI. :func:`get`, :func:`post`, :func:`patch`, :func:`put` and 

301 :func:`delete` set the method and the status code for you. 

302 """ 

303 

304 def store_args_decorator(func: Callable[..., Any]) -> Callable[..., Any]: 

305 # Create a new attribute: '_api_route_args' 

306 func._api_route_args = (path, api_route_kwargs) # type: ignore[attr-defined] 

307 return func 

308 

309 return store_args_decorator 

310 

311 

312def get(path: str, **api_route_kwargs: Any) -> Callable[..., Any]: 

313 """Decorator to mark a View method as a GET endpoint. 

314 

315 Equivalent to:: 

316 

317 @route(path, methods=["GET"], status_code=200, ... ) 

318 """ 

319 api_route_kwargs.setdefault("methods", ["GET"]) 

320 api_route_kwargs.setdefault("status_code", 200) 

321 return route(path, **api_route_kwargs) 

322 

323 

324def post(path: str, **api_route_kwargs: Any) -> Callable[..., Any]: 

325 """Decorator to mark a View method as a POST endpoint. 

326 

327 Equivalent to:: 

328 

329 @route(path, methods=["POST"], status_code=201, ... ) 

330 """ 

331 api_route_kwargs.setdefault("methods", ["POST"]) 

332 api_route_kwargs.setdefault("status_code", 201) 

333 return route(path, **api_route_kwargs) 

334 

335 

336def put(path: str, **api_route_kwargs: Any) -> Callable[..., Any]: 

337 """Decorator to mark a View method as a PUT endpoint. 

338 

339 Equivalent to:: 

340 

341 @route(path, methods=["PUT"], status_code=200, ... ) 

342 """ 

343 api_route_kwargs.setdefault("methods", ["PUT"]) 

344 api_route_kwargs.setdefault("status_code", 200) 

345 return route(path, **api_route_kwargs) 

346 

347 

348def patch(path: str, **api_route_kwargs: Any) -> Callable[..., Any]: 

349 """Decorator to mark a View method as a PATCH endpoint. 

350 

351 Equivalent to:: 

352 

353 @route(path, methods=["PATCH"], status_code=200, ... ) 

354 """ 

355 api_route_kwargs.setdefault("methods", ["PATCH"]) 

356 api_route_kwargs.setdefault("status_code", 200) 

357 return route(path, **api_route_kwargs) 

358 

359 

360def delete(path: str, **api_route_kwargs: Any) -> Callable[..., Any]: 

361 """Decorator to mark a View method as a DELETE endpoint. 

362 

363 Equivalent to:: 

364 

365 @route(path, methods=["DELETE"], status_code=204, ... ) 

366 """ 

367 api_route_kwargs.setdefault("methods", ["DELETE"]) 

368 api_route_kwargs.setdefault("status_code", 204) 

369 return route(path, **api_route_kwargs) 

370 

371 

372@dataclasses.dataclass(frozen=True, eq=False) 

373class _ModifiedRoute: 

374 """What :func:`modify_route` returns. When the class is defined, a copy of 

375 the inherited route takes its place.""" 

376 

377 path: str | None 

378 api_route_kwargs: dict[str, Any] 

379 

380 

381def modify_route(path: str | None = None, **api_route_kwargs: Any) -> Any: 

382 """Change the options of a route that the view inherits, and keep the rest. 

383 

384 Use it in the class body, under the name of the route method:: 

385 

386 class TagView(fr.AsyncRestView): 

387 prefix = "/tags" 

388 model = Tag 

389 

390 create_endpoint = fr.modify_route(status_code=200, name="create_tag") 

391 delete_endpoint = fr.modify_route(dependencies=[Depends(require_admin)]) 

392 

393 It takes the arguments of a route decorator, such as :func:`post`: they go 

394 to FastAPI's ``APIRouter.add_api_route()``. ``path`` replaces the path of 

395 the route. 

396 

397 Each argument replaces the one of the inherited route. ``dependencies`` and 

398 ``responses`` add up, as they do on a view. ``dependencies`` run base first. 

399 ``responses`` add up per status code, and a status code set to ``None`` is 

400 left out. A status code without a body, such as 204, also removes the 

401 response model of the route. 

402 

403 It changes how a route is served, not what it sends. So 

404 ``response_model`` and the other ``response_model_*`` arguments raise 

405 :class:`~fastapi_restly.exc.RestlyConfigurationError`. To change the 

406 response of the view, set ``response_schema`` or ``list_response_schema``. 

407 To change the response of one route, write the route method. 

408 

409 This changes the route of this view and its subclasses. The route of the 

410 base class stays the same. 

411 

412 A name that is not an inherited route raises 

413 :class:`~fastapi_restly.exc.RestlyConfigurationError` when the class is 

414 defined. 

415 """ 

416 refused = sorted( 

417 name 

418 for name in api_route_kwargs 

419 if name == "response_model" or name.startswith("response_model_") 

420 ) 

421 if refused: 

422 raise RestlyConfigurationError( 

423 f"fr.modify_route cannot set {refused[0]}: it changes how a route is " 

424 "served, not what it sends. To change the response of the view, set " 

425 "response_schema or list_response_schema. To change the response of " 

426 "one route, write the route method." 

427 ) 

428 return _ModifiedRoute(path, api_route_kwargs) 

429 

430 

431def _apply_modified_routes(cls: type) -> None: 

432 """Put a copy of the inherited route in the place of each 

433 :func:`modify_route` that ``cls`` gets. 

434 

435 So the attribute is a normal route for the rest of Restly, and 

436 ``super().create_endpoint(...)`` finds a function. A plain mixin holds its 

437 options until a view class takes them, so this reads every class in the 

438 MRO: for each name, the options in front of the first method. 

439 """ 

440 names = { 

441 name 

442 for klass in cls.__mro__ 

443 for name, value in vars(klass).items() 

444 if isinstance(value, _ModifiedRoute) 

445 } 

446 for name in sorted(names): 

447 owners = [klass for klass in cls.__mro__ if name in vars(klass)] 

448 values = [vars(klass)[name] for klass in owners] 

449 options = list( 

450 itertools.takewhile(lambda v: isinstance(v, _ModifiedRoute), values) 

451 ) 

452 for index in range(len(options), len(values)): 

453 later = values[index + 1 :] 

454 if isinstance(values[index], _ModifiedRoute) and not any( 

455 hasattr(value, "_api_route_args") for value in later 

456 ): 

457 raise RestlyConfigurationError( 

458 f"{cls.__name__}.{name}: the fr.modify_route of " 

459 f"{owners[index].__name__} changes nothing, because " 

460 f"{owners[index].__name__} comes after the class with the " 

461 f"route. Put {owners[index].__name__} before the view " 

462 f"class in the bases of {cls.__name__}." 

463 ) 

464 if not options: 

465 continue 

466 endpoint = values[len(options)] if len(values) > len(options) else None 

467 if endpoint is None and len(values) > len(options): 

468 raise RestlyConfigurationError( 

469 f"{cls.__name__}.{name} uses fr.modify_route, but " 

470 f"{owners[len(options)].__name__} sets {name} to None, so there " 

471 f"is no route to change." 

472 ) 

473 if not hasattr(endpoint, "_api_route_args"): 

474 raise RestlyConfigurationError( 

475 f"{cls.__name__}.{name} uses fr.modify_route, but the class " 

476 f"inherits no route method with this name. Use the name of a " 

477 f"route method, such as create_endpoint." 

478 ) 

479 path, route_kwargs = endpoint._api_route_args # type: ignore[union-attr] 

480 route_kwargs = dict(route_kwargs) 

481 dropped = getattr(endpoint, "_dropped_response_model", None) 

482 if dropped is not None: 

483 route_kwargs.pop("response_model", None) 

484 route_kwargs.update(dropped) 

485 for option in reversed(options): 

486 path = path if option.path is None else option.path 

487 for key, value in option.api_route_kwargs.items(): 

488 if key == "dependencies": 

489 value = _added_dependencies(route_kwargs.get(key), value) 

490 elif key == "responses": 

491 value = {**(route_kwargs.get(key) or {}), **(value or {})} 

492 route_kwargs[key] = value 

493 # The inherited response model belongs to a status with a body, and 

494 # FastAPI refuses a response model on a status without one. A subclass 

495 # with a status with a body gets the model back, see above. 

496 dropped = None 

497 if not is_body_allowed_for_status_code(route_kwargs.get("status_code")): 

498 dropped = { 

499 key: value 

500 for key, value in route_kwargs.items() 

501 if key == "response_model" 

502 } 

503 route_kwargs["response_model"] = None 

504 copied = _copy_route(endpoint, cls, name) 

505 copied._api_route_args = (path, route_kwargs) # type: ignore[attr-defined] 

506 copied._dropped_response_model = dropped # type: ignore[attr-defined] 

507 copied._from_modify_route = True # type: ignore[attr-defined] 

508 # Delete first: in the class dict, a name keeps its first place. The routes 

509 # that the class writes come first, see the copy of the inherited routes. 

510 if name in vars(cls): 

511 delattr(cls, name) 

512 setattr(cls, name, copied) 

513 

514 

515def _added_dependencies(dependencies: Any, new: Any) -> list[Any]: 

516 """``dependencies``, then ``new``. A dependency that ``new`` lists again 

517 moves to where ``new`` lists it, so what comes before it still runs first.""" 

518 added = list(dependencies or ()) 

519 for dependency in new or (): 

520 added = [seen for seen in added if seen is not dependency] 

521 added.append(dependency) 

522 return added 

523 

524 

525#: The routes that load one row by the id in the path. 

526_ITEM_ROUTES = ("get_one_endpoint", "update_endpoint", "delete_endpoint", "put") 

527 

528 

529def _check_composite_key(cls: Any) -> None: 

530 """Refuse item routes on a model with a composite primary key and the 

531 default ``where_id``: an id from the path cannot name one row.""" 

532 if len(sa_inspect(cls.model).primary_key) < 2: 

533 return 

534 if getattr(cls.where_id, "__module__", "").startswith("fastapi_restly."): 

535 routes = [name for name in _ITEM_ROUTES if _serves_route(cls, name)] 

536 if routes: 

537 raise RestlyConfigurationError( 

538 f"{cls.__name__}: {cls.model.__name__} has a composite primary " 

539 f"key, so an id from the path cannot name one row, and the " 

540 f"item routes ({', '.join(routes)}) need it. Set " 

541 "id_type = str, and override where_id(id): split the id, and " 

542 "return sqlalchemy.and_(Model.a == a, Model.b == b). Or leave " 

543 "the item routes out, such as get_one_endpoint = None." 

544 ) 

545 

546 

547def _check_actions(cls: type) -> None: 

548 """Refuse a view whose ``Action`` does not inherit from the ``Action`` of 

549 a base class. 

550 

551 Each class that declares ``Action`` adds actions, and a view's ``Action`` 

552 must have all of them: the view's own class, or a mixin's, or two bases 

553 that each declare one, where Python takes the first and drops the other. 

554 """ 

555 action = cls.Action # type: ignore[attr-defined] 

556 declared: list[tuple[type, Any]] = [] 

557 for klass in cls.__mro__: 

558 if "Action" not in vars(klass): 

559 continue 

560 value = vars(klass)["Action"] 

561 if all(value is not seen for _, seen in declared): 

562 declared.append((klass, value)) 

563 for klass, value in declared: 

564 if not (isinstance(value, type) and issubclass(value, Action)): 

565 raise RestlyConfigurationError( 

566 f"{cls.__name__}.Action{_origin(cls, klass)} does not inherit " 

567 "from fr.Action. Declare it as class Action(fr.Action)." 

568 ) 

569 missing = [ 

570 (klass, base) for klass, base in declared if not issubclass(action, base) 

571 ] 

572 if not missing: 

573 return 

574 # the classes to inherit from: the bases' Action classes, without one 

575 # that another of them already inherits from 

576 bases = [(klass, base) for klass, base in declared if klass is not cls] 

577 keep = [ 

578 _action_class_name(klass, base) 

579 for klass, base in bases 

580 if not any(other is not base and issubclass(other, base) for _, other in bases) 

581 ] 

582 raise RestlyConfigurationError( 

583 f"{cls.__name__}.Action{_set_by(cls, 'Action')} does not inherit from " 

584 f"{', '.join(_action_class_name(klass, base) for klass, base in missing)}. " 

585 "A view's Action has all the actions of its bases. " 

586 f"Declare it on {cls.__name__} with every base: " 

587 f"class Action({', '.join(keep)})." 

588 ) 

589 

590 

591def _action_class_name(klass: type, action: type) -> str: 

592 """How a message names the ``Action`` that ``klass`` declares.""" 

593 return "fr.Action" if action is Action else f"{klass.__name__}.Action" 

594 

595 

596def _check_action_name(view: Any, action: Any) -> None: 

597 """Raise ``ValueError`` when ``write_action`` gets an action that the 

598 view's ``Action`` does not declare.""" 

599 if _declares(type(view).Action, action): 

600 return 

601 name = type(view).__name__ 

602 raise ValueError( 

603 f"{name}.write_action({action!r}, ...): unknown action {action!r}. " 

604 f"{name}.Action does not declare it." 

605 ) 

606 

607 

608class BaseRestView( 

609 View, Generic[ModelT, ResponseSchemaT, CreateSchemaT, UpdateSchemaT, IdT] 

610): 

611 """ 

612 The part that :class:`RestView` and :class:`AsyncRestView` share: the 

613 settings, the read statement and the response methods. 

614 

615 It has no routes, no handlers and no business methods. Those are on 

616 ``RestView`` and ``AsyncRestView``, in a sync and an async form. Subclass 

617 this class only to write a CRUD base class of your own. 

618 """ 

619 

620 # The view's actions: the names that authorize and the transaction hooks 

621 # get. A view with actions of its own declares a subclass of fr.Action 

622 # with this name. (The docs show fr.Action, not this attribute.) 

623 Action = Action 

624 

625 #: The main schema: the Pydantic class that lists the fields of the 

626 #: resource. Restly builds :attr:`response_schema`, :attr:`create_schema` 

627 #: and :attr:`update_schema` from it. When a view sets none, Restly 

628 #: generates it from :attr:`model` with 

629 #: :func:`~fastapi_restly.schemas.derive_schema`. 

630 schema: ClassVar[type[pydantic.BaseModel]] = _DEFAULT_SETTINGS["schema"] 

631 #: The class of everything that goes out: the single responses, the 

632 #: items of the list response, and the fields the list params filter and 

633 #: sort on. The relationships it names are the ones the view loads. When 

634 #: a view sets none, Restly builds it with 

635 #: :func:`~fastapi_restly.schemas.derive_response_schema`: the main 

636 #: schema without its ``WriteOnly`` fields, named ``<Resource>Response``. 

637 #: A class that a view sets is used as it is. 

638 response_schema: ClassVar[type[pydantic.BaseModel]] = _DEFAULT_SETTINGS[ 

639 "response_schema" 

640 ] 

641 #: The class of the list response: what ``GET /`` and a route that 

642 #: declares :data:`~fastapi_restly.views.ViewListResponse` send. When a 

643 #: view sets none, Restly builds it with 

644 #: :func:`~fastapi_restly.schemas.derive_list_response_schema`: the 

645 #: envelope of the view's :attr:`pagination`, with the response schema as 

646 #: its items, named ``<Resource>ListResponse``. Restly fills a class that 

647 #: a view sets as it fills an envelope: by field name, from the values of 

648 #: the view's pagination, such as ``data``, ``total_count``, ``page``, 

649 #: ``page_size`` and ``total_pages``. A view that replaces 

650 #: ``get_many_endpoint`` can set any type here. 

651 list_response_schema: ClassVar[Any] = _DEFAULT_SETTINGS["list_response_schema"] 

652 #: The class of the ``POST`` body. When a view sets none, Restly builds 

653 #: it from the main schema without its ``ReadOnly`` fields and without 

654 #: a primary key that the server generates. It is named 

655 #: ``<Resource>Create``. A class that a view sets is used as it is. 

656 create_schema: ClassVar[type[pydantic.BaseModel]] = _DEFAULT_SETTINGS[ 

657 "create_schema" 

658 ] 

659 #: The class of the ``PATCH`` body. When a view sets none, Restly builds 

660 #: it from the main schema without its ``ReadOnly`` fields and without 

661 #: a primary key that the server generates, and makes every other field 

662 #: optional. It is named ``<Resource>Update``. A class that a view sets 

663 #: is used as it is. 

664 update_schema: ClassVar[type[pydantic.BaseModel]] = _DEFAULT_SETTINGS[ 

665 "update_schema" 

666 ] 

667 #: The SQLAlchemy model that the view serves: a mapped class. A view that 

668 #: you register needs it. A class that is not mapped raises 

669 #: :class:`~fastapi_restly.exc.RestlyConfigurationError` when Python 

670 #: creates the view class. 

671 model: ClassVar[type[Any]] 

672 #: The clause every read on this view applies: list, count, and retrieve 

673 #: (a row outside it is 404). ``None`` (the default) falls back to the 

674 #: model's declared ``default_scope``; ``fr.clauses.UNSCOPED`` reads 

675 #: unscoped despite that default. Declaring a scope replaces the default, 

676 #: it does not stack on it; compose the replacement from the same leaves 

677 #: (``ItemClauses.trashed`` containing the tenant clause ``visible`` 

678 #: contains). A rule that must hold under every scope is a session-level 

679 #: ``with_loader_criteria``, not a view concern (see the Multi-Tenancy 

680 #: guide). See the Scopes guide for scopes. 

681 scope: ClassVar[WhereClause | None] = None 

682 #: The type of the ``{id}`` path parameter on the default routes. ``None`` 

683 #: (the default) takes the Python type of the model's primary key, and a 

684 #: composite key gets ``int``. Set a type to override it. Built-in item 

685 #: routes use Starlette's ``int`` or ``uuid`` path converter for those 

686 #: types. Integer paths accept non-negative digits. An unmatched value 

687 #: falls through to another route or returns 404, instead of 422. 

688 id_type: ClassVar[type[Any] | None] = None 

689 #: What a list route does with a query key that it does not read. 

690 #: ``"forbid"`` (the default) rejects the request with 422, so a typo in 

691 #: a filter key does not return more rows than the client asked for. 

692 #: ``"ignore"`` leaves the key out, as FastAPI does. The values are those of 

693 #: Pydantic's ``extra`` setting. The same rule applies to a ``QueryParams`` 

694 #: that a method gets as list params. 

695 unknown_query_params: ClassVar[Literal["forbid", "ignore"]] = "forbid" 

696 #: How list endpoints paginate. The default :class:`NumberedPagination` 

697 #: takes ``page`` / ``page_size`` query parameters, runs the count query, 

698 #: and wraps the list in its ``envelope`` (:class:`NumberedEnvelope`: 

699 #: ``data`` plus ``total_count`` / ``page`` / ``page_size`` / 

700 #: ``total_pages``). An :class:`OffsetPagination` does the same with 

701 #: ``limit`` / ``offset`` query parameters (:class:`OffsetEnvelope`: 

702 #: ``data`` plus ``total_count`` / ``limit`` / ``offset``). A 

703 #: :class:`NoPagination` returns every matching row 

704 #: with no count, in its ``envelope``; ``None`` is short for 

705 #: ``NoPagination()``, a plain :class:`Envelope` (``data`` only). A view 

706 #: inherits it, so a project base view sets it once; a view that differs 

707 #: changes one setting with ``replace()`` on the shared settings. For a 

708 #: shape no envelope model can express, such as a header, replace 

709 #: ``get_many_endpoint`` with a matching ``response_model`` (see 

710 #: :class:`AsyncReactAdminView`). 

711 pagination: ClassVar[Pagination | None] = _DEFAULT_PAGINATION 

712 #: The filter keys that the list params keep, from the keys that Restly 

713 #: generates from :attr:`response_schema`. An entry is a key with the 

714 #: Python name of its field, such as ``"name__icontains"``, also for a 

715 #: field with an alias, or a pattern. ``*`` 

716 #: matches any characters except ``.``, so ``"created_at__*"`` is every 

717 #: filter on ``created_at`` with a suffix, and ``"vendor.*"`` is every 

718 #: key on the fields of ``vendor``. The default, ``("*",)``, keeps the 

719 #: keys of the resource's own fields, and no dotted keys. ``()`` keeps 

720 #: none. An entry that the view sets and that matches no key fails when 

721 #: the view registers. So does an entry with the name in the URL of a 

722 #: field with an alias, also when the view inherits it. 

723 include_filters: ClassVar[tuple[str, ...]] = ("*",) 

724 #: The filter keys that the list params leave out, after 

725 #: :attr:`include_filters`. The entries are the same as there, but a name 

726 #: without a suffix leaves out the whole field: the plain key and each key 

727 #: with a suffix. So ``("name",)`` also removes ``name__in``. 

728 exclude_filters: ClassVar[tuple[str, ...]] = () 

729 #: The keys that ``sort`` accepts: the Python name of a field, such as 

730 #: ``"name"`` or ``"vendor.name"``, or a pattern as in 

731 #: :attr:`include_filters`. The 

732 #: default, ``("*",)``, is the resource's own fields. A sort key never goes 

733 #: through a to-many relationship. With ``()``, the list has no ``sort`` 

734 #: parameter. 

735 include_sort_keys: ClassVar[tuple[str, ...]] = ("*",) 

736 #: The sort keys to leave out, after :attr:`include_sort_keys`. 

737 exclude_sort_keys: ClassVar[tuple[str, ...]] = () 

738 #: The name of the sort parameter. Set it to keep the URLs of another 

739 #: library, such as ``"ordering"`` for Django REST framework or 

740 #: ``"order_by"`` for fastapi-filter. The old name is then free for a 

741 #: filter key. 

742 sort_query_param: ClassVar[str] = "sort" 

743 #: The sort when the request has none, written as ``?sort=`` with the 

744 #: Python names of the fields, such as ``"-created_at"``. It becomes the 

745 #: default of the sort parameter, with the names in the URL, so OpenAPI 

746 #: shows it. A key must be a field of :attr:`response_schema` that a sort 

747 #: key could have, but :attr:`include_sort_keys` does not have to keep 

748 #: it. Use each key only once. ``None`` (the default) sorts by the primary 

749 #: key. The primary key is always the last term. A view that inherits it 

750 #: and does not have all its keys fails when it registers. 

751 default_sort: ClassVar[str | None] = None 

752 #: Where a sort puts NULLs: ``"last"`` (the default) or ``"first"`` in 

753 #: both directions, on every database. ``None`` leaves them where the 

754 #: database puts them, which differs: PostgreSQL puts them last in an 

755 #: ascending sort, SQLite and MySQL first. 

756 sort_nulls: ClassVar[SortNulls] = "last" 

757 #: The list params (filter, sort, page) as a pydantic model, generated 

758 #: from ``response_schema`` and ``model`` by 

759 #: :func:`~fastapi_restly.query.derive_list_params_schema`. Any route 

760 #: method on the view that declares a ``list_params`` parameter takes it: 

761 #: typed for FastAPI and OpenAPI, and guarded against unknown keys like 

762 #: ``GET /``, so a custom list route (a trash route naming its own scope) 

763 #: reads the same list params. The route can take other query parameters 

764 #: beside it. 

765 list_params_schema: ClassVar[type[pydantic.BaseModel]] = _DEFAULT_SETTINGS[ 

766 "list_params_schema" 

767 ] 

768 

769 #: Whether each write action of this view is one transaction. ``True`` (the 

770 #: default) refuses a ``session.commit()`` in the action, and an error undoes 

771 #: all of its work. ``False`` allows that commit, for code that must keep it, 

772 #: such as a library, or a function that a job also calls. All else stays, 

773 #: but the action is no longer one transaction: what is committed stays 

774 #: saved when a later step raises, and ``after_action_commit`` does not run 

775 #: then. There is no savepoint, so an error rolls back all that is not 

776 #: committed, also the work of the route before the action. The outermost 

777 #: write action decides for the actions inside it, and an outermost 

778 #: ``shared_write_action_commit()`` block always refuses a commit. See "Code 

779 #: that must commit in a write action" in the Lifecycle guide. 

780 atomic_write_actions: ClassVar[bool] = True 

781 

782 #: The ``fastapi.Request`` of the current request, which Restly sets for 

783 #: each request. After :func:`include_view`, a view that you create 

784 #: yourself must get ``request=`` (``None`` outside a request) and 

785 #: ``session=``. 

786 request: fastapi.Request 

787 

788 if not TYPE_CHECKING: 788 ↛ 802line 788 didn't jump to line 802 because the condition on line 788 was always true

789 # Hidden from type checkers, which report an unknown name themselves. 

790 

791 def __getattr__(self, name: str) -> Any: 

792 """Name the replacement of a removed or renamed view method, so an 

793 old call such as ``self.make_new_object(data)`` says what to use.""" 

794 if inspect.getattr_static(type(self), name, None) is not None: 

795 # the name exists: its own getter raised AttributeError, so 

796 # raise that error again rather than hide it 

797 return object.__getattribute__(self, name) 

798 raise AttributeError( 

799 _missing_view_attribute(type(self).__name__, name), name=name, obj=self 

800 ) 

801 

802 def __init_subclass__(cls, **kwargs: Any) -> None: 

803 super().__init_subclass__(**kwargs) 

804 _drop_stale_settings(cls) 

805 _reject_bare_verb_route_names(cls) 

806 # validate at class definition, so a raw expression fails at 

807 # import instead of on the first read 

808 scope = cls.__dict__.get("scope") 

809 if not (scope is None or isinstance(scope, WhereClause)): 

810 raise RestlyConfigurationError( 

811 f"{cls.__name__}.scope must be a WhereClause, " 

812 f"fr.clauses.UNSCOPED, or None, got {type(scope).__name__}; " 

813 "wrap a raw expression with where_clause()" 

814 ) 

815 # the annotation accepts any class, so the mapping is checked here 

816 model = cls.__dict__.get("model") 

817 if model is not None and not is_mapped_class(model): 

818 label = getattr(model, "__name__", repr(model)) 

819 raise RestlyConfigurationError( 

820 f"{cls.__name__}.model must be a SQLAlchemy mapped class, " 

821 f"got {label}, which has no mapper" 

822 ) 

823 # build_query is removed; a definition would be silently dead code, 

824 # and dead visibility filtering is a security hole 

825 for klass in cls.__mro__: 

826 if "build_query" in vars(klass): 

827 origin = _origin(cls, klass) 

828 raise RestlyConfigurationError( 

829 f"{cls.__name__} defines build_query{origin}, which is " 

830 "removed and no longer called. Declare visibility as a " 

831 "clause: default_scope on the model's ClauseNamespace, or " 

832 "the scope attribute on the view. Reshape a list in " 

833 "apply_list_params, and relationship loading in " 

834 "get_loader_options. See Migrating from " 

835 "build_query in the Scopes guide." 

836 ) 

837 # delete_object is removed; a stale soft-delete override would be 

838 # silently dead code, and a dead soft delete is a hard delete 

839 for klass in cls.__mro__: 

840 if "delete_object" in vars(klass): 

841 origin = _origin(cls, klass) 

842 raise RestlyConfigurationError( 

843 f"{cls.__name__} defines delete_object{origin}, which is " 

844 "removed and no longer called. Override delete instead: a " 

845 "soft delete flips a timestamp there. A raw row delete is " 

846 "fr.objects.delete_object / async_delete_object on " 

847 "self.session." 

848 ) 

849 # the view's domain utilities are removed: a definition here would 

850 # be dead code, and nothing would say so 

851 for klass in cls.__mro__: 

852 for name, instead in _REMOVED_DOMAIN_UTILITIES.items(): 

853 if name in vars(klass): 

854 origin = _origin(cls, klass) 

855 raise RestlyConfigurationError( 

856 f"{cls.__name__} defines {name}{origin}, which was " 

857 f"removed from the view and is no longer called. " 

858 f"{instead} For another model, use " 

859 f"fr.objects.{name} or async_{name}. A value that " 

860 "every write path must set belongs on the model, as a " 

861 "column default or a mapper event." 

862 ) 

863 # the loads are final: an override could drop the scope of a read, 

864 # and it was also the load of every write 

865 for klass in cls.__mro__: 

866 if klass.__module__.startswith("fastapi_restly."): 

867 continue 

868 for name, instead in _FINAL_LOADS.items(): 

869 if name in vars(klass): 

870 origin = _origin(cls, klass) 

871 raise RestlyConfigurationError( 

872 f"{cls.__name__} defines {name}{origin}, which you " 

873 f"cannot override. {instead}" 

874 ) 

875 _check_load_hooks(cls) 

876 # the handlers are final: an override re-implements the load, 

877 # authorize and commit order to reach something another seam gives 

878 # directly, and a generated route could then skip either 

879 for klass in cls.__mro__: 

880 if klass.__module__.startswith("fastapi_restly."): 

881 continue 

882 for name in _FINAL_HANDLERS: 

883 if name in vars(klass): 

884 origin = _origin(cls, klass) 

885 raise RestlyConfigurationError( 

886 _final_handler_message(cls.__name__, name, origin) 

887 ) 

888 _check_pagination_setting(cls) 

889 _check_list_settings(cls) 

890 _check_unknown_query_params(cls) 

891 _check_atomic_write_actions(cls) 

892 _check_renamed_names(cls) 

893 _check_actions(cls) 

894 

895 def _apply_scope(self, stmt: Select[Any], scope: ReadScope) -> Select[Any]: 

896 # the one path every read takes, so retrieve, list and count cannot 

897 # disagree about which rows exist; not an override point 

898 if scope is None: 

899 scope = resolve_scope(self) 

900 else: 

901 # a per-read scope replaces the resolution rather than joining it 

902 scope = _checked_scope(scope, type(self).__name__, "a per-read scope") 

903 return apply_clauses(stmt, scope) 

904 

905 def _narrowed_scope(self, scope: ReadScope, where: _ReadWhere) -> ReadScope: 

906 # the list handler is final, so it can fold where= into the scope it 

907 # forwards: get_many keeps one visibility input, and an override 

908 # keeps its signature 

909 if where is None: 

910 return scope 

911 label = type(self).__name__ 

912 if scope is None: 

913 scope = resolve_scope(self) 

914 else: 

915 scope = _checked_scope(scope, label, "a per-read scope") 

916 return all_of(scope, _checked_where(where, label)) 

917 

918 @final 

919 def select(self, *, scope: ReadScope = None) -> Select[Any]: 

920 """The statement of the view's rows: ``select(model)``, the scope, 

921 and :meth:`get_loader_options`. 

922 

923 ``get_one`` and ``get_many`` start here, and so does a custom route 

924 that builds its own read: ``self.select().where(Item.price > 10)``. 

925 The rows are the ones the view shows, and each row loads what the 

926 response needs. You cannot override it: set ``scope`` to change the 

927 rows, and override 

928 :meth:`get_loader_options` to change the loads. 

929 

930 :param scope: a clause that replaces the view scope for this 

931 statement; ``fr.clauses.UNSCOPED`` reads past it. 

932 """ 

933 stmt = self._apply_scope(sa_select(self.model), scope) 

934 options = self.get_loader_options() 

935 return stmt.options(*options) if options else stmt 

936 

937 def where_id(self, id: Any) -> ColumnElement[bool]: 

938 """The WHERE that picks the row an id from a path names. 

939 

940 The default compares the primary key: ``Item.id == id``. Override 

941 to find the row by another key, such as a slug. Every load by id 

942 uses it: ``GET``, ``PATCH`` and ``DELETE /{id}``, and 

943 ``self.get_one(id)`` in your routes:: 

944 

945 def where_id(self, id: str) -> ColumnElement[bool]: 

946 return Recipe.slug == id 

947 

948 A model with a composite primary key needs an override: set 

949 ``id_type = str``, split the id from the path, and return 

950 ``and_(...)``. The expression must name 

951 the view's model, not another table, and it runs no query, so define 

952 it with ``def``, also on an async view. 

953 """ 

954 return _primary_key_criterion(self.model, id) 

955 

956 def not_found(self, id: Any) -> Exception: 

957 """The exception for an id that names no row: a 404 by default, such 

958 as ``User with id 5 was not found``. The name is the resource of the 

959 main schema, as in the names of the schemas that Restly generates. 

960 

961 ``get_one`` raises what this returns, so an override can change the 

962 text or the status, such as ``410`` for a row that was deleted. On 

963 an async view it may be ``async def``, and Restly awaits it. ``id`` 

964 is the id from the path, or ``None`` when a route loaded by an 

965 expression, such as ``handle_get_one(Item.slug == slug)``. 

966 """ 

967 return NotFound(_not_found_message(_schema_resource_name(self.schema), id)) 

968 

969 def _row_criterion(self, id: Any) -> ColumnElement[bool]: 

970 """The WHERE of ``get_one``: an expression that a route passes in 

971 place of the id, or :meth:`where_id` of the id.""" 

972 name = type(self).__name__ 

973 if isinstance(id, ColumnElement): 

974 _check_identity_tables(self.model, id, name) 

975 return id 

976 _reject_bad_row_identity(name, id) 

977 criterion = _clause_element(self.where_id(id)) 

978 if not ( 

979 isinstance(criterion, ColumnElement) and isinstance(criterion.type, Boolean) 

980 ): 

981 raise TypeError( 

982 f"{name}.where_id must return a SQL condition, such as " 

983 f"Model.slug == id, got {type(criterion).__name__}." 

984 ) 

985 _check_identity_tables(self.model, criterion, f"{name}.where_id") 

986 return criterion 

987 

988 def get_loader_options(self) -> list[Any]: 

989 """The loader options of every read: what each row loads. 

990 

991 The default is a recursive ``selectinload(...)`` for each 

992 relationship that :attr:`response_schema` names. :meth:`select` 

993 applies them, so ``get_one``, ``get_many`` and your routes load the 

994 same, and so does the reload after the save of a write. Override to 

995 load more: a relationship that the response schema does not name, or 

996 a ``query_expression`` through ``with_expression(...)``. Add to 

997 ``super().get_loader_options()`` to keep the default loads. See 

998 "Return related objects in a response" on the Relationships guide 

999 page. 

1000 """ 

1001 return _build_relationship_loader_options( 

1002 self.model, type(self).response_schema 

1003 ) 

1004 

1005 def _get_reload_statements(self, subject: Any, others: list[Any]) -> list[Any]: 

1006 """The SELECTs that make the saved rows of a write ready for the 

1007 hooks and the response. 

1008 

1009 Called by the save step of the commit bracket after the flush and the 

1010 refresh of the subject. One reload covers the subject, when the view 

1011 has loader options, and the other rows of the view's model that the 

1012 action wrote. So a value that only the loader options load, such as 

1013 a relationship that ``to_single_response`` reads or a 

1014 ``with_expression``, is there after every write, and a route that 

1015 changes several rows returns each of them as the database has it. 

1016 The view's scope does not apply: a row that the write moved out of 

1017 it, such as a soft-deleted row, is still the row that the action 

1018 returns. 

1019 """ 

1020 rows = list(others) 

1021 options = self.get_loader_options() 

1022 if options and isinstance(subject, self.model): 

1023 if sa_inspect(subject).persistent: 

1024 rows.insert(0, subject) 

1025 if not rows: 

1026 return [] 

1027 return _rows_reload_statements(self.model, rows, options) 

1028 

1029 def _reject_unknown_query_params(self) -> None: 

1030 """Reject any query-string key that neither the list params nor the 

1031 route reads. 

1032 

1033 Runs before every route that declares ``list_params`` (see 

1034 :attr:`list_params_schema`). 

1035 

1036 The list params dependency (:func:`_list_params_dependency`) reads 

1037 their keys and ignores any other, which would let typoed 

1038 filters or unsupported operators (e.g. 

1039 ``active__gte=true`` on a boolean column where the schema does not 

1040 emit a range operator) widen the result set without telling the 

1041 caller. We treat unknown keys as a validation error instead, mirroring 

1042 FastAPI's 422 envelope shape so the response is consistent with 

1043 bound-violation errors, unless :attr:`unknown_query_params` is 

1044 ``"ignore"``. 

1045 

1046 No-op when there is no live request, as when code calls a route 

1047 method directly, outside an HTTP request. Then there is no URL to 

1048 check, and the caller is responsible for what it passes. 

1049 """ 

1050 request = getattr(self, "request", None) 

1051 if request is None: 1051 ↛ 1052line 1051 didn't jump to line 1052 because the condition on line 1051 was never true

1052 return 

1053 params_model = _list_params_schema(type(self)) 

1054 list_keys = {key for key, _, _ in _list_params_fields(params_model)} 

1055 self._reject_unknown_keys(request.query_params, list_keys) 

1056 

1057 def _reject_unknown_keys(self, query: QueryParams, allowed: set[str]) -> None: 

1058 """Raise a 422 for a key of ``query`` that is not in ``allowed``, and 

1059 that the route does not read. 

1060 

1061 Does nothing when :attr:`unknown_query_params` is ``"ignore"``. 

1062 """ 

1063 if self.unknown_query_params == "ignore": 

1064 return 

1065 reject_unknown_query_keys(query, allowed, getattr(self, "request", None)) 

1066 

1067 def _validated_list_params(self, list_params: Any) -> Any: 

1068 """``list_params`` as the list route gives them. 

1069 

1070 A ``QueryParams`` or a mapping goes through :attr:`list_params_schema` 

1071 first, as on the list route. A ``QueryParams`` is the query of a 

1072 request, so it can also hold keys that the route reads. Those are 

1073 left out, and any other key is unknown, as on the list route (see 

1074 :attr:`unknown_query_params`). A mapping holds list params only, so 

1075 a key that they do not have is an error. Anything else is list 

1076 params already, such as a Pydantic model, which is validated. A view 

1077 that is not registered gets the list params that registration would 

1078 set. 

1079 """ 

1080 if not isinstance(list_params, Mapping): 

1081 return list_params 

1082 params_model = _list_params_schema(type(self)) 

1083 if isinstance(list_params, QueryParams): 

1084 keys = {key for key, _, _ in _list_params_fields(params_model)} 

1085 self._reject_unknown_keys(list_params, keys) 

1086 list_params = QueryParams( 

1087 [ 

1088 (key, value) 

1089 for key, value in list_params.multi_items() 

1090 if key in keys 

1091 ] 

1092 ) 

1093 return _validate_raw_list_params(params_model, list_params) 

1094 

1095 def _filter_method_values(self, list_params: Any) -> list[tuple[_OwnFilter, Any]]: 

1096 """The filter methods to call for ``list_params``, each with its value. 

1097 

1098 The class of ``list_params`` records its filter methods. Other list 

1099 params, such as a Pydantic model of your own, record none, so the 

1100 view's filter methods do not run. A warning then names them. 

1101 """ 

1102 record = _record_of(type(list_params)) 

1103 params_model = _list_params_schema(type(self)) 

1104 if type(list_params) is not params_model: 

1105 own = _record_of(params_model) 

1106 skipped = [ 

1107 own_filter.method 

1108 for own_filter in (own.own_filters if own else ()) 

1109 if record is None or own_filter not in record.own_filters 

1110 ] 

1111 if skipped: 

1112 methods = "methods" if len(skipped) > 1 else "method" 

1113 verb = "do" if len(skipped) > 1 else "does" 

1114 warnings.warn( 

1115 f"{type(self).__name__} got list params of the class " 

1116 f"{type(list_params).__name__}, so its filter {methods} " 

1117 f"{', '.join(skipped)} {verb} not run. Only an instance of " 

1118 "its list_params_schema runs the filter methods. Pass one, " 

1119 "or pass a dict or a QueryParams, which Restly validates " 

1120 "through list_params_schema.", 

1121 RestlySkippedFilterMethodsWarning, 

1122 stacklevel=3, 

1123 ) 

1124 return record.own_filter_values(list_params) if record else [] 

1125 

1126 def to_single_response(self, obj: ModelT | ResponseSchemaT) -> ResponseSchemaT: 

1127 """Serialize one ORM object to the view's :attr:`response_schema`. 

1128 

1129 By default the response schema is the main schema without its 

1130 WriteOnly fields, named like ``UserResponse``. An override may return 

1131 an instance of another model, such as :attr:`schema`. Only the fields 

1132 of the response schema go out. Restly copies the values of an instance 

1133 of a subclass of the response schema, and of :attr:`schema` when 

1134 Restly derived the response schema, without validating them again. It 

1135 validates any other model into the response schema from its 

1136 attributes. 

1137 

1138 The view loads only the relationships that the response schema names. 

1139 An override that builds :attr:`schema` from the ORM object also reads 

1140 the relationships of its WriteOnly fields. On an async view that fails 

1141 with ``MissingGreenlet``: add them in 

1142 :meth:`get_loader_options`, or build the response schema 

1143 instead. 

1144 

1145 The ORM path below validates through the response schema, so a view's 

1146 main schema that declares a WriteOnly field the ORM object doesn't carry 

1147 (e.g. ``password`` backed by a ``password_hash`` column) doesn't fail 

1148 response validation. It validates in lax mode, also for a strict 

1149 class, so a strict ``float`` field reads the text ``"NaN"`` that a 

1150 JSON column stores. 

1151 """ 

1152 response_schema = type(self).response_schema 

1153 response = _as_response(response_schema, obj) 

1154 if isinstance(response, response_schema): 

1155 return cast(ResponseSchemaT, response) 

1156 

1157 # Build a payload of raw attribute values keyed by schema field name; 

1158 # re-validating it below serializes each field through its own type. The 

1159 # response schema's ``from_attributes`` config resolves nested schemas and 

1160 # reference types (IDRef/IDSchema) straight from the ORM rows, with no 

1161 # view-layer special-casing. Alias rendering happens when FastAPI 

1162 # serializes the response model. 

1163 payload: dict[str, Any] = {} 

1164 for field_name, field_info in response_schema.model_fields.items(): 

1165 if hasattr(obj, field_name): 

1166 payload[field_name] = getattr(obj, field_name) 

1167 elif field_info.alias and hasattr(obj, field_info.alias): 1167 ↛ 1168line 1167 didn't jump to line 1168 because the condition on line 1167 was never true

1168 payload[field_name] = getattr(obj, field_info.alias) 

1169 

1170 # Lax mode, also for a strict class, as a PydanticJSON column reads 

1171 # its document: a JSON column holds the text "NaN" for a float. 

1172 adapter = _response_adapter(response_schema) 

1173 return cast( 

1174 ResponseSchemaT, 

1175 adapter.validate_python( 

1176 payload, by_alias=False, by_name=True, strict=False 

1177 ), 

1178 ) 

1179 

1180 def _single_response(self, obj: Any) -> pydantic.BaseModel: 

1181 """One object as an instance of the response schema. An override of 

1182 :meth:`to_single_response` may return an instance of another model.""" 

1183 return _as_response(type(self).response_schema, self.to_single_response(obj)) 

1184 

1185 def to_list_response(self, list_result: ListResult[ModelT]) -> Any: 

1186 """Build the list response body: an instance of 

1187 :attr:`list_response_schema`. 

1188 

1189 By default this class is the ``envelope`` of the view's 

1190 :attr:`pagination`: a :class:`NumberedEnvelope` (``data`` plus 

1191 ``total_count`` / ``page`` / ``page_size`` / ``total_pages``), an 

1192 :class:`OffsetEnvelope` (``data`` plus ``total_count`` / ``limit`` / 

1193 ``offset``), or an :class:`Envelope` (``data`` only) for a view 

1194 without pagination. To 

1195 change the shape, set :attr:`list_response_schema` or the pagination's 

1196 ``envelope``. A list type, such as ``list[UserSummary]``, gives a list 

1197 without the page values. For a ``Content-Range`` header, see 

1198 :class:`AsyncReactAdminView`: it overrides this method and sets 

1199 :attr:`list_response_schema` to match. 

1200 

1201 The values of the page come from ``list_result.list_params``. 

1202 """ 

1203 data = [self._single_response(obj) for obj in list_result.objects] 

1204 pagination = _settings_of(self.pagination) 

1205 envelope = type(self).list_response_schema 

1206 if not _is_pydantic_class(envelope): 

1207 return _type_adapter(envelope).validate_python( 

1208 data, from_attributes=True, by_alias=False, by_name=True 

1209 ) 

1210 values = ( 

1211 _list_params_values(list_result.list_params, pagination=self.pagination) 

1212 if pagination._has_pages 

1213 else {} 

1214 ) 

1215 return _build_envelope( 

1216 envelope, pagination._page_info(data, list_result.total_count or 0, values) 

1217 ) 

1218 

1219 def snapshot(self, obj: Any) -> dict[str, Any]: 

1220 """The column values that are loaded on ``obj``, passed as ``old`` to 

1221 ``before_action_commit`` and ``after_action_commit`` to compare old 

1222 and new values. 

1223 

1224 The default is :func:`~fastapi_restly.objects.snapshot`: a shallow 

1225 copy, which shares a mutable value, such as a JSON dict, with the 

1226 object. Override it to change what ``old`` holds, for example the 

1227 state of a relationship before the change. 

1228 """ 

1229 return _object_snapshot(obj) 

1230 

1231 @classmethod 

1232 def _check_schema_settings(cls) -> None: 

1233 """Each schema setting holds a Pydantic class, or a function that gives 

1234 one. Another value would fail only on a request, or not at all.""" 

1235 for name in _DEFAULT_SETTINGS: 

1236 value = getattr(cls, name) 

1237 marker = _schema_type_in(value) 

1238 if marker is not None: 

1239 raise RestlyConfigurationError( 

1240 f"{cls.__name__}.{name} is {value!r}, which uses {marker!r}. " 

1241 "A setting cannot hold a marker, as Restly fills a marker in " 

1242 "a route. Write a function: " 

1243 f"{name} = SchemaType(lambda view: ...), and read " 

1244 "view.response_schema in it." 

1245 ) 

1246 if name == "list_response_schema": 

1247 continue # any type, see _check_list_response_schema 

1248 if _is_pydantic_class(value): 

1249 where = f"{cls.__name__}.{name}" 

1250 if name == "schema": 

1251 _reject_table_class( 

1252 value, 

1253 where, 

1254 "Leave `schema` out, and Restly generates it from the " 

1255 "model. Or set a class without `table=True`.", 

1256 ) 

1257 elif name in ("create_schema", "update_schema"): 

1258 _reject_table_class( 

1259 value, 

1260 where, 

1261 f"Remove {name}, and Restly generates it from the `schema` " 

1262 "of the view. Or set a class without `table=True`.", 

1263 ) 

1264 continue 

1265 if isinstance(inspect.getattr_static(cls, name), SchemaType): 

1266 raise RestlyConfigurationError( 

1267 f"The SchemaType function of {cls.__name__}.{name} must " 

1268 f"return a Pydantic class, but it returned {value!r}. A route " 

1269 "can use another type: put the SchemaType in the annotation " 

1270 "of the route." 

1271 ) 

1272 raise RestlyConfigurationError( 

1273 f"{cls.__name__}.{name} must be a Pydantic class or a " 

1274 f"fastapi_restly.views.SchemaType, got {value!r}." 

1275 ) 

1276 

1277 @classmethod 

1278 def _check_write_schemas(cls) -> None: 

1279 """A write schema that a route of the view takes holds no SQLModel table 

1280 class in a field that a client can write.""" 

1281 for name, routes in _WRITE_SCHEMA_ROUTES: 

1282 if any(_serves_route(cls, route) for route in routes): 

1283 _reject_writable_table_class( 

1284 getattr(cls, name), f"{cls.__name__}.{name}" 

1285 ) 

1286 

1287 @classmethod 

1288 def _check_table_subclasses(cls) -> None: 

1289 """No schema of the view holds a subclass of a SQLModel table class, as 

1290 OpenAPI would show that class with no required fields.""" 

1291 for name in _DEFAULT_SETTINGS: 

1292 if name != "list_params_schema": 

1293 _reject_table_subclass(getattr(cls, name), f"{cls.__name__}.{name}") 

1294 

1295 @classmethod 

1296 def _check_list_response_schema(cls) -> None: 

1297 """A class that the default ``GET /`` cannot fill fails here, and not 

1298 on the first request.""" 

1299 if _uses_default(cls, "list_response_schema"): 

1300 return 

1301 label = f"{cls.__name__}.list_response_schema" 

1302 value = cls.list_response_schema 

1303 if value is None: 

1304 raise RestlyConfigurationError( 

1305 f"{label} is None. It must be a type, such as " 

1306 "NumberedEnvelope[UserSummary] or list[UserSummary]." 

1307 ) 

1308 if _has_items_without_a_type(value): 

1309 raise RestlyConfigurationError( 

1310 f"{label} is the generic class {value.__name__} without a type for " 

1311 "its items, so OpenAPI would show items without a type. Write " 

1312 f"{value.__name__}[UserSummary]." 

1313 ) 

1314 # A view that replaces what fills the class decides what the class is. 

1315 endpoint = getattr(cls, "get_many_endpoint", None) 

1316 if ( 

1317 endpoint is None 

1318 or not endpoint.__module__.startswith("fastapi_restly.") 

1319 or not cls.to_list_response.__module__.startswith("fastapi_restly.") 

1320 or not _serves_route(cls, "get_many_endpoint") 

1321 ): 

1322 return 

1323 other_shape = " For another shape, replace get_many_endpoint." 

1324 if _is_pydantic_class(value): 

1325 sample = _settings_of(cls.pagination)._page_info_sample() 

1326 _check_fillable(label, value, sample, other_shape) 

1327 elif get_origin(value) not in (list, collections.abc.Sequence): 

1328 raise RestlyConfigurationError( 

1329 f"{label} must be a Pydantic class or a list type for the default " 

1330 f"GET /, got {value!r}.{other_shape}" 

1331 ) 

1332 item = _list_item_annotation(value) 

1333 if item is not None and item is not Any and _list_item_class(value) is None: 

1334 raise RestlyConfigurationError( 

1335 f"The items of {label} must be a Pydantic class for the default " 

1336 f"GET /, got {item!r}. Restly fills the items from the response " 

1337 f"class.{other_shape}" 

1338 ) 

1339 response = cls.response_schema 

1340 lacking = _fields_the_items_lack(value, response) 

1341 if lacking: 

1342 raise RestlyConfigurationError( 

1343 f"The items of {label} have fields that {response.__name__} does " 

1344 f"not have: {', '.join(lacking)}. Restly fills the items from the " 

1345 f"response schema, so add these fields to it.{other_shape}" 

1346 ) 

1347 

1348 @classmethod 

1349 def _check_declared_list_params_schema(cls) -> None: 

1350 """Reject declared list params that do not follow the view's settings. 

1351 

1352 Restly generates list params from the pagination, the list settings 

1353 and the filter methods. A subclass that changes one of them gets new 

1354 list params only when the declared ones are what Restly would 

1355 generate for the class that declares them (see 

1356 ``_generated_for``). Otherwise the declared list params stay, and 

1357 must fit the view. List params from ``derive_list_params_schema`` 

1358 must have the view's settings: other settings give other keys than 

1359 the view says. Hand-written list params take no settings and no 

1360 filter methods, and have the page fields of the view's pagination. 

1361 """ 

1362 declared = _DeclaredListParams(cls, _owner(cls, "list_params_schema")) 

1363 record = _record_of(cls.list_params_schema) 

1364 if record is None: 

1365 declared.check_hand_written() 

1366 declared.check_pages() 

1367 declared.check_keys() 

1368 else: 

1369 declared.check_derived(record) 

1370 

1371 @classmethod 

1372 def before_include_view(cls): 

1373 """ 

1374 Apply type annotations needed for FastAPI, before creating an APIRouter from 

1375 this view and registering it. 

1376 

1377 This function can be overridden to further tweak the endpoints before they 

1378 are added to FastAPI. 

1379 """ 

1380 _check_pagination_setting(cls) 

1381 _check_renamed_names(cls) 

1382 

1383 if not hasattr(cls, "model"): 

1384 if _uses_default(cls, "schema"): 

1385 raise ValueError( 

1386 f"'{cls.__name__}.model' must be specified to auto-generate schema" 

1387 ) 

1388 if _uses_default(cls, "list_params_schema"): 1388 ↛ 1393line 1388 didn't jump to line 1393 because the condition on line 1388 was always true

1389 raise ValueError( 

1390 f"'{cls.__name__}.model' must be specified: it is needed to " 

1391 "generate the list params." 

1392 ) 

1393 cls._check_schema_settings() 

1394 cls._check_write_schemas() 

1395 cls._check_table_subclasses() 

1396 cls._check_list_response_schema() 

1397 if not _uses_default(cls, "list_params_schema"): 

1398 cls._check_declared_list_params_schema() 

1399 

1400 # Every route that declares ``list_params`` takes the view's list 

1401 # params: ``GET /`` and any custom list route alike, guarded the same 

1402 # way. The guard checks keys against ``list_params_schema`` whatever 

1403 # the annotation says, so they replace an explicit annotation too. A 

1404 # dependency reads them rather than a FastAPI query model, which 

1405 # collapses next to any other query parameter (see 

1406 # :func:`_list_params_dependency`). 

1407 params_model = _list_params_schema(cls) 

1408 list_params = Annotated[ 

1409 params_model, fastapi.Depends(_list_params_dependency(params_model)) 

1410 ] 

1411 for name, route in list(cls.__dict__.items()): 

1412 if not hasattr(route, "_api_route_args"): 

1413 continue 

1414 if "list_params" in _route_parameters(route) and not getattr( 

1415 route, "_fr_list_guard", False 

1416 ): 

1417 route = _guard_list_params(route) 

1418 setattr(cls, name, route) 

1419 _fill_schema_types(route, cls, list_params) 

1420 _check_composite_key(cls) 

1421 

1422 

1423#: Whether the list params that a class declares are the ones that Restly 

1424#: would generate for it. 

1425@dataclasses.dataclass(frozen=True) 

1426class _DeclaredListParams: 

1427 """The checks of the list params that a view declares, and the words 

1428 that their messages share.""" 

1429 

1430 cls: type 

1431 #: The class that declares the list params: the view or a base class. 

1432 declarer: type 

1433 

1434 @property 

1435 def origin(self) -> str: 

1436 """`` (from AppView)`` when a base class declares the list params.""" 

1437 return _origin(self.cls, self.declarer) 

1438 

1439 @property 

1440 def its(self) -> str: 

1441 return f"its list_params_schema{self.origin}" 

1442 

1443 @property 

1444 def out(self) -> str: 

1445 """What to leave out to have the list params generated, after 

1446 "Leave" or "leave".""" 

1447 of = "" if self.declarer is self.cls else f" of {self.declarer.__name__}" 

1448 return f"list_params_schema out{of} to have it generated" 

1449 

1450 def below(self, setter: type) -> bool: 

1451 """Whether ``setter`` is a subclass of the declaring class.""" 

1452 mro = self.cls.__mro__ 

1453 return mro.index(setter) < mro.index(self.declarer) 

1454 

1455 def remove(self, name: str, setter: type) -> str: 

1456 if setter is self.cls: 

1457 return "Remove the setting" 

1458 return f"Remove {name} from {setter.__name__}" 

1459 

1460 def check_hand_written(self) -> None: 

1461 """Hand-written list params take no filter methods and no list 

1462 settings.""" 

1463 for name, method in _list_filter_methods(self.cls).items(): 

1464 raise self._filter_method_error( 

1465 name, method._fr_list_filter, "is written by hand" 

1466 ) 

1467 for name, default in _LIST_SETTING_DEFAULTS.items(): 

1468 if _list_setting(self.cls, name) != default: 

1469 raise self._setting_error( 

1470 name, 

1471 "is written by hand, so Restly cannot apply the setting", 

1472 expected=default, 

1473 on_declarer=self.remove(name, self.declarer), 

1474 ) 

1475 

1476 def check_pages(self) -> None: 

1477 """Hand-written list params of a view with pages have the page fields 

1478 of its pagination, or the list does not page while its response says 

1479 that it has pages. The same holds for a page size or a limit with the 

1480 default ``None``. ``fr.query.PagedListParams`` and 

1481 ``fr.query.OffsetListParams`` get the fields from the pagination, and 

1482 a subclass cannot declare them again. A view that builds its list 

1483 response itself, as a react-admin view does, pages in its own way.""" 

1484 list_params = self.cls.list_params_schema 

1485 pagination = getattr(self.cls, "pagination", None) 

1486 base = _page_fields_base(list_params) 

1487 if base is not None: 

1488 needed = type(_PAGINATION_OF_BASE[base]).__name__ 

1489 if not _takes_page_fields(list_params, pagination): 

1490 raise RestlyConfigurationError( 

1491 f"{self.cls.__name__}.list_params_schema{self.origin} is a " 

1492 f"fr.query.{base.__name__}, which needs a fr.{needed}, but the " 

1493 f"pagination of the view is {pagination!r}. Set a fr.{needed}, " 

1494 "or let the list params subclass pydantic.BaseModel." 

1495 ) 

1496 for name in _redeclared_page_fields(list_params, base): 

1497 raise RestlyConfigurationError( 

1498 f"{self.cls.__name__}.list_params_schema{self.origin} declares " 

1499 f"the field {name!r} again. A view gives this field the settings " 

1500 "of its pagination, so your default and bounds would have no " 

1501 f"effect. Set them on the fr.{needed} of the view, or let the " 

1502 "list params subclass pydantic.BaseModel." 

1503 ) 

1504 return 

1505 settings = _settings_of(pagination) 

1506 if not settings._has_pages: 

1507 return 

1508 if self.cls.to_list_response is not BaseRestView.to_list_response: 

1509 return 

1510 keys = {key for key, _, _ in _list_params_fields(list_params)} 

1511 missing = [name for name in settings._query_params() if name not in keys] 

1512 if missing: 

1513 fields = " and no ".join(repr(name) for name in missing) 

1514 raise RestlyConfigurationError( 

1515 f"{self.cls.__name__}.list_params_schema{self.origin} has no " 

1516 f"{fields} field, so the list would not page while its response " 

1517 f"says that it has pages. {settings._own_list_params_advice}" 

1518 ) 

1519 limit_param = settings._row_limit_query_param() 

1520 for key, field, _ in _list_params_fields(list_params): 

1521 if key == limit_param and field.default is None: 

1522 raise RestlyConfigurationError( 

1523 f"{self.cls.__name__}.list_params_schema{self.origin} gives the " 

1524 f"field {key!r} the default None, so a request without it would " 

1525 "return every row while its response says that it has pages. " 

1526 "Give the field a number as its default. " 

1527 f"{settings._own_list_params_advice}" 

1528 ) 

1529 

1530 def check_keys(self) -> None: 

1531 """Each field of hand-written list params has its own query key. One 

1532 value would fill the fields of a shared key, and OpenAPI would show the 

1533 key twice, which it does not allow.""" 

1534 keys = [key for key, _, _ in _list_params_fields(_list_params_schema(self.cls))] 

1535 for key in keys: 

1536 if keys.count(key) > 1: 

1537 raise RestlyConfigurationError( 

1538 f"{self.cls.__name__}.list_params_schema{self.origin} has more " 

1539 f"than one field with the query key {key!r}. One value would " 

1540 "fill them all, and OpenAPI would show the key twice. Rename a " 

1541 "field, or the parameter of the pagination." 

1542 ) 

1543 

1544 def check_derived(self, record: Any) -> None: 

1545 """List params from ``derive_list_params_schema`` have the view's 

1546 filter methods, list settings and pagination: other ones give other 

1547 keys than the view says.""" 

1548 recorded = [(own.key, own.method) for own in record.own_filters] 

1549 methods = [ 

1550 (method._fr_list_filter, name) 

1551 for name, method in _list_filter_methods(self.cls).items() 

1552 ] 

1553 for key, name in methods: 1553 ↛ 1554line 1553 didn't jump to line 1554 because the loop on line 1553 never started

1554 if (key, name) not in recorded: 

1555 raise self._filter_method_error(name, key, "was created without it") 

1556 others = [key for key, name in recorded if (key, name) not in methods] 

1557 if others: 

1558 # the list params of another view, with its filter methods 

1559 raise RestlyConfigurationError( 

1560 f"{self.cls.__name__}.list_params_schema{self.origin} has the " 

1561 "keys of filter methods that the view does not have: " 

1562 f"{', '.join(others)}. Leave {self.out}." 

1563 ) 

1564 for name in _LIST_SETTING_DEFAULTS: 

1565 value = _list_setting(self.cls, name) 

1566 expected = getattr(record, name) 

1567 if value != expected: 

1568 raise self._setting_error( 

1569 name, 

1570 f"was created with {name}={expected!r}. A view's settings " 

1571 "must be the ones that its list params were created with", 

1572 expected=expected, 

1573 on_declarer=f"Create it with {name}={value!r}", 

1574 ) 

1575 if _query_settings(record.pagination) != _query_settings(self.cls.pagination): 

1576 setter = _owner(self.cls, "pagination") 

1577 if self.below(setter): 

1578 fix = ( 

1579 f"{self.remove('pagination', setter)}, or declare " 

1580 f"list_params_schema on {setter.__name__} as well, created " 

1581 "with its pagination" 

1582 ) 

1583 elif self.cls.pagination is _DEFAULT_PAGINATION: 1583 ↛ 1584line 1583 didn't jump to line 1584 because the condition on line 1583 was never true

1584 fix = f"Create it with the default pagination, or leave {self.out}" 

1585 else: 

1586 fix = ( 

1587 f"Create it with the pagination of {setter.__name__}, or " 

1588 f"leave {self.out}" 

1589 ) 

1590 raise RestlyConfigurationError( 

1591 f"{self.cls.__name__}.list_params_schema{self.origin} was " 

1592 f"created for other pagination settings than the view's. {fix}." 

1593 ) 

1594 

1595 def _filter_method_error( 

1596 self, name: str, key: str, kind: str 

1597 ) -> RestlyConfigurationError: 

1598 setter = _owner(self.cls, name) 

1599 fix = f"Leave {self.out}" 

1600 if setter is not self.declarer and not self.below(setter): 1600 ↛ 1602line 1600 didn't jump to line 1602 because the condition on line 1600 was always true

1601 fix += f", or set {name} = None on {self.declarer.__name__} to drop it" 

1602 return RestlyConfigurationError( 

1603 f"{self.cls.__name__} has the filter method {name}" 

1604 f"{_origin(self.cls, setter)}, but {self.its} {kind}. Restly adds " 

1605 f"the key {key!r} of a filter method only to list params that it " 

1606 f"generates. {fix}." 

1607 ) 

1608 

1609 def _setting_error( 

1610 self, name: str, problem: str, *, expected: Any, on_declarer: str 

1611 ) -> RestlyConfigurationError: 

1612 """The error for a list setting of the view that the list params do 

1613 not have. 

1614 

1615 :param on_declarer: The fix when the declarer sets the setting. 

1616 """ 

1617 value = _list_setting(self.cls, name) 

1618 setter = _owner(self.cls, name) 

1619 if self.below(setter): 

1620 fix = ( 

1621 f"{self.remove(name, setter)}, or declare list_params_schema on " 

1622 f"{setter.__name__} as well, created by " 

1623 f"fr.query.derive_list_params_schema() with {name}={value!r}" 

1624 ) 

1625 elif setter is self.declarer: 

1626 fix = f"{on_declarer}, or leave {self.out}" 

1627 else: 

1628 fix = ( 

1629 f"Set {name} = {expected!r} on {self.declarer.__name__}, or " 

1630 f"leave {self.out}" 

1631 ) 

1632 return RestlyConfigurationError( 

1633 f"{self.cls.__name__} {_how_set(self.cls, name)}, but {self.its} " 

1634 f"{problem}. {fix}." 

1635 ) 

1636 

1637 

1638#: A ``BaseRestView`` at any parameterization, for the signature below. 

1639_AnyRestView = BaseRestView[Any, Any, Any, Any, Any] 

1640 

1641 

1642def resolve_scope(target: type[Any] | _AnyRestView) -> WhereClause: 

1643 """The scope a read applies, resolved down the ladder. 

1644 

1645 Pass a view, class or instance, for the visibility that view's reads 

1646 apply: its declared 

1647 :attr:`scope <fastapi_restly.views.BaseRestView.scope>`, the model's 

1648 ``default_scope`` when the view declares none, and 

1649 ``fr.clauses.UNSCOPED`` when neither does. Pass a mapped model class 

1650 for the model rung alone, which is what every reference check applies. 

1651 The two answers differ wherever a view declares a scope, so code off 

1652 the request path that wants what the API shows passes the view. 

1653 

1654 The result is a clause or ``fr.clauses.UNSCOPED``, never ``None``, so 

1655 it composes without a branch:: 

1656 

1657 stmt = fr.apply_clauses( 

1658 select(Task).where(Task.project_id == id), 

1659 fr.resolve_scope(TaskView), 

1660 ) 

1661 

1662 Every read resolves here, so a route that applies the result sees the 

1663 same rows as 

1664 :meth:`get_one <fastapi_restly.views.RestView.get_one>` and 

1665 :meth:`get_many <fastapi_restly.views.RestView.get_many>`. It resolves 

1666 the scope and does not apply it: applying stays with the framework, 

1667 and there is no apply-side override point. 

1668 

1669 :param target: a view class or instance, or a mapped model class. 

1670 :raises RestlyConfigurationError: if the declared scope is not a clause. 

1671 :raises TypeError: if ``target`` is neither a view nor a mapped model. 

1672 """ 

1673 label = target.__name__ if isinstance(target, type) else type(target).__name__ 

1674 if is_mapped_class(target): 

1675 return _model_scope(target) 

1676 if not isinstance(target, BaseRestView) and not ( 

1677 isinstance(target, type) and issubclass(target, BaseRestView) 

1678 ): 

1679 raise TypeError( 

1680 "resolve_scope() takes a RestView / AsyncRestView class or instance, " 

1681 f"or a mapped model class, got {label}" 

1682 ) 

1683 declared = target.scope 

1684 if declared is None: 

1685 return _model_scope(target.model) 

1686 # backstop for a post-definition assignment; the declared form is 

1687 # validated in __init_subclass__ 

1688 return _checked_scope(declared, label, "the scope") 

1689 

1690 

1691def _guard_list_params(route: Callable) -> Callable: 

1692 """Run the unknown-key guard before a route that takes ``list_params``. 

1693 

1694 A copy, like the parent-endpoint copies: it keeps the route args and the 

1695 signature, and it passes on its arguments as it gets them. The marker keeps 

1696 a subclass's copy from being wrapped twice. 

1697 """ 

1698 self_name = next(iter(inspect.signature(route).parameters)) 

1699 if inspect.iscoroutinefunction(route): 

1700 

1701 async def _async_guarded(*args, **kwargs): 

1702 (args[0] if args else kwargs[self_name])._reject_unknown_query_params() 

1703 return await route(*args, **kwargs) 

1704 

1705 guarded: Callable = _async_guarded 

1706 else: 

1707 

1708 def _sync_guarded(*args, **kwargs): 

1709 (args[0] if args else kwargs[self_name])._reject_unknown_query_params() 

1710 return route(*args, **kwargs) 

1711 

1712 guarded = _sync_guarded 

1713 

1714 guarded = _wrap_endpoint(guarded, route) 

1715 guarded._fr_list_guard = True # type: ignore[attr-defined] 

1716 return guarded 

1717 

1718 

1719def _is_pydantic_class(value: Any) -> bool: 

1720 return isinstance(value, type) and issubclass(value, pydantic.BaseModel) 

1721 

1722 

1723@functools.cache 

1724def _type_adapter(annotation: Any) -> pydantic.TypeAdapter[Any]: 

1725 return pydantic.TypeAdapter(annotation) 

1726 

1727 

1728def _list_item_type(annotation: Any) -> Any: 

1729 """``X`` for ``list[X]`` and ``Sequence[X]``, also with ``| None``. Or 

1730 ``None``.""" 

1731 annotation, _ = _without_none(annotation) 

1732 if get_origin(annotation) not in (list, collections.abc.Sequence): 1732 ↛ 1733line 1732 didn't jump to line 1733 because the condition on line 1732 was never true

1733 return None 

1734 return next(iter(get_args(annotation)), None) 

1735 

1736 

1737def _has_items_without_a_type(list_response: Any) -> bool: 

1738 """Whether ``list_response`` is a generic class that was not given the type of 

1739 its items, such as ``NumberedEnvelope``.""" 

1740 if not _is_pydantic_class(list_response): 

1741 return False 

1742 field = list_response.model_fields.get("data") 

1743 return field is not None and isinstance(_list_item_type(field.annotation), TypeVar) 

1744 

1745 

1746def _list_item_annotation(list_response: Any) -> Any: 

1747 """The type of the items of a list response: ``X`` for ``list[X]`` and for a 

1748 class with a field ``data: list[X]``. Or ``None``.""" 

1749 annotation = list_response 

1750 if _is_pydantic_class(list_response): 

1751 field = list_response.model_fields.get("data") 

1752 annotation = None if field is None else field.annotation 

1753 return _list_item_type(annotation) 

1754 

1755 

1756def _list_item_class(list_response: Any) -> type[pydantic.BaseModel] | None: 

1757 """The Pydantic class of the items of a list response, also for ``X | None`` 

1758 or ``Annotated[X, ...]``. Or ``None``.""" 

1759 item, _ = _without_none(_bare(_list_item_annotation(list_response))) 

1760 item = _bare(item) 

1761 return item if _is_pydantic_class(item) else None 

1762 

1763 

1764def _fields_the_items_lack( 

1765 list_response: Any, response: type[pydantic.BaseModel] 

1766) -> list[str]: 

1767 """The fields without a default of the items of ``list_response`` that 

1768 ``response`` has neither as a field nor as an attribute. A validator that 

1769 runs before the fields may fill them, so such a class is not looked at.""" 

1770 item = _list_item_class(list_response) 

1771 if item is None or any( 

1772 validator.info.mode == "before" 

1773 and not validator.func.__module__.startswith("fastapi_restly.") 

1774 for validator in item.__pydantic_decorators__.model_validators.values() 

1775 ): 

1776 return [] 

1777 return [ 

1778 name 

1779 for name, item_field in item.model_fields.items() 

1780 if item_field.is_required() 

1781 and name not in response.model_fields 

1782 and not hasattr(response, name) 

1783 ] 

1784 

1785 

1786#: Each write schema of a CRUD view, and the routes that take it. The PUT route 

1787#: of a react-admin view takes the update schema too. 

1788_WRITE_SCHEMA_ROUTES = ( 

1789 ("create_schema", ("create_endpoint",)), 

1790 ("update_schema", ("update_endpoint", "put")), 

1791) 

1792 

1793 

1794def _serves_route(view_cls: type, method_name: str) -> bool: 

1795 """True if the view has a route method ``method_name``. A view leaves out 

1796 an inherited route with ``method_name = None``.""" 

1797 return hasattr(getattr(view_cls, method_name, None), "_api_route_args") 

1798 

1799 

1800def _copy_route(endpoint: Callable, view_cls: type, name: str) -> Callable: 

1801 """A copy of a route of a base class, for ``view_cls`` to hold as ``name``.""" 

1802 copied = _make_copy(endpoint) 

1803 if getattr(endpoint, "__module__", "").startswith("fastapi_restly."): 

1804 # The shells carry override-redirect docstrings for help()/source 

1805 # readers. FastAPI reads endpoint.__doc__ as the OpenAPI operation 

1806 # description, so strip the copy: framework guidance must not leak 

1807 # into the user's API docs. User-defined endpoints keep theirs. 

1808 copied.__doc__ = None 

1809 # Set explicit __qualname__ for debugging purposes. 

1810 copied.__qualname__ = f"{view_cls.__name__}_{name}_wrapper" 

1811 return copied 

1812 

1813 

1814def _make_copy(endpoint: Callable) -> Callable: 

1815 """ 

1816 Wrap the endpoint in a new function as kind of copy. 

1817 

1818 The copy passes on its arguments as it gets them. FastAPI calls an endpoint 

1819 with keyword arguments only, ``self`` too, and a decorator on the method must 

1820 see that same call. slowapi, for one, fails when ``self`` alone is positional. 

1821 

1822 Fun fact: You cannot do this inside a for loop, because the closure of 'endpoint' 

1823 inside the wrapper works on the variable, not on the value. And for-loops in Python 

1824 do not have their own variable scope. 

1825 

1826 https://eev.ee/blog/2011/04/24/gotcha-python-scoping-closures/ 

1827 """ 

1828 if inspect.iscoroutinefunction(endpoint): 

1829 

1830 async def _async_wrapper(*args, **kwargs): 

1831 return await endpoint(*args, **kwargs) 

1832 

1833 endpoint_wrapper: Callable = _async_wrapper 

1834 else: 

1835 

1836 def _sync_wrapper(*args, **kwargs): 

1837 return endpoint(*args, **kwargs) 

1838 

1839 endpoint_wrapper = _sync_wrapper 

1840 

1841 return _wrap_endpoint(endpoint_wrapper, endpoint) 

1842 

1843 

1844def _wrap_endpoint(wrapper: Callable, endpoint: Callable) -> Callable: 

1845 """Copy the endpoint's metadata and globals onto a wrapper.""" 

1846 # FastAPI 0.115 resolves string annotations against the wrapper's 

1847 # globals; FastAPI 0.128 and later unwrap the endpoint first. These 

1848 # wrappers read only their arguments and closure, so the endpoint's 

1849 # globals can replace this module's without changing what they do. 

1850 copied = types.FunctionType( 

1851 wrapper.__code__, 

1852 inspect.unwrap(endpoint).__globals__, 

1853 wrapper.__name__, 

1854 wrapper.__defaults__, 

1855 wrapper.__closure__, 

1856 ) 

1857 functools.update_wrapper(copied, endpoint) 

1858 copied.__annotations__ = endpoint.__annotations__.copy() 

1859 return copied