Coverage for fastapi_restly/views/_react_admin.py: 99%

171 statements  

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

1""" 

2React Admin compatible views for fastapi-restly. 

3 

4Implements the ra-data-simple-rest HTTP contract for list: 

5- response body: plain JSON array 

6- sort: sort=["field","ASC|DESC"] 

7- range: range=[start, end] (both inclusive, e.g. [0,24] = 25 items) 

8- filter: filter={"field":"value"} or filter={"id":[1,2,3]} for getMany 

9- Content-Range: items 0-24/315 

10 

11The views are a user of Restly. They have list params of their own, and use 

12the public API, as a view of yours would. A comment names the ticket of each 

13private name that has no public form yet. 

14""" 

15 

16import inspect 

17from typing import Any, ClassVar, Literal, Protocol, cast, get_origin 

18 

19import fastapi 

20import pydantic 

21import sqlalchemy 

22from fastapi.exceptions import RequestValidationError 

23 

24from fastapi_restly.exc import RestlyConfigurationError 

25from fastapi_restly.query import FilterKey, SortKey, SortNulls, order_by_primary_key 

26from fastapi_restly.views import ( 

27 AsyncRestView, 

28 BaseRestView, 

29 IDType, 

30 ListResult, 

31 NumberedPagination, 

32 Pagination, 

33 RestView, 

34 SchemaType, 

35 ViewListResponse, 

36 ViewResponse, 

37 ViewUpdate, 

38 get, 

39 put, 

40) 

41 

42# Private names without a public form yet. 

43from ._guards import _owner, _set_by 

44from ._list_params import _how_set, _list_filter_methods, _list_setting 

45 

46#: Default page size used when the react-admin client does not send a `range` 

47#: query parameter. Override per view with 

48#: ``pagination = fr.NumberedPagination(default_page_size=...)``. 

49DEFAULT_REACT_ADMIN_PAGE_SIZE = 25 

50 

51#: The largest SQL offset: a database takes a signed 64-bit integer. 

52_MAX_OFFSET = 2**63 - 1 

53 

54#: The settings of a ``NumberedPagination`` that react-admin does not use. 

55_UNUSED_PAGINATION_SETTINGS = ( 

56 "max_page", 

57 "page_query_param", 

58 "page_size_query_param", 

59 "envelope", 

60) 

61 

62#: The view settings that choose the keys of generated list params. 

63_LIST_SETTINGS = ( 

64 "include_filters", 

65 "exclude_filters", 

66 "include_sort_keys", 

67 "exclude_sort_keys", 

68 "sort_query_param", 

69 "default_sort", 

70) 

71 

72 

73class ReactAdminListParams(pydantic.BaseModel): 

74 """The list params of a react-admin view: ``sort``, ``range`` and 

75 ``filter``. 

76 

77 React-admin sends each key as JSON in the query string. The fields are 

78 :class:`pydantic.Json <pydantic.types.Json>`, so the view and your 

79 overrides get the parsed 

80 values: ``sort`` as ``("name", "DESC")``, ``range`` as ``(0, 24)`` and 

81 ``filter`` as a dict. JSON that does not have this shape gets a ``422`` 

82 that names the place, as a bad value of other list params does. 

83 

84 To add a query key, such as a search key, subclass this class and set the 

85 subclass as the view's ``list_params_schema``. 

86 """ 

87 

88 #: The sort order: a field name and ``"ASC"`` or ``"DESC"``, such as 

89 #: ``("name", "DESC")``. ``None`` when the request has no sort. 

90 sort: pydantic.Json[tuple[str, Literal["ASC", "DESC"]]] | None = pydantic.Field( 

91 None, 

92 description='The sort order, as JSON: ["field", "ASC"] or ["field", "DESC"].', 

93 ) 

94 #: The first and the last row to return, both included, such as 

95 #: ``(0, 24)``. ``None`` when the request has no range. 

96 range: pydantic.Json[tuple[int, int]] | None = pydantic.Field( 

97 None, 

98 description=( 

99 "The rows to return, as JSON: [start, end]. Both rows are " 

100 "included, and the first row is 0." 

101 ), 

102 ) 

103 #: The filters, as a dict from a field name to a value. ``None`` when 

104 #: the request has no filter. 

105 filter: pydantic.Json[dict[str, Any]] | None = pydantic.Field( 

106 None, 

107 description=( 

108 'The filters, as JSON: {"field": value}. A list of values, as in ' 

109 '{"id": [1, 2, 3]}, matches each of them.' 

110 ), 

111 ) 

112 

113 @pydantic.field_validator("range") 

114 @classmethod 

115 def _check_range(cls, value: tuple[int, int] | None) -> tuple[int, int] | None: 

116 if value is None: 116 ↛ 117line 116 didn't jump to line 117 because the condition on line 116 was never true

117 return value 

118 start, end = value 

119 if start < 0: 

120 raise ValueError("the start of the range is less than 0") 

121 if end < start: 

122 raise ValueError("the end of the range comes before its start") 

123 if end > _MAX_OFFSET: 

124 # The database takes a signed 64-bit offset. 

125 raise ValueError(f"the end of the range is more than {_MAX_OFFSET}") 

126 return value 

127 

128 

129# --------------------------------------------------------------------------- 

130# Query helpers (standalone, analogous to query/_impl.py) 

131# --------------------------------------------------------------------------- 

132 

133 

134def _apply_react_admin_filters( 

135 stmt: sqlalchemy.Select, model: type[Any], schema_cls: Any, filters: dict 

136) -> sqlalchemy.Select: 

137 """Apply a react-admin filter dict to a select statement. A list of 

138 values matches each of them.""" 

139 for name, value in filters.items(): 

140 key = FilterKey(model, schema_cls, name) 

141 if isinstance(value, list): 

142 stmt = stmt.where(_is_one_of(key.column, [key.parse(v) for v in value])) 

143 else: 

144 stmt = stmt.where(key.column == key.parse(value)) 

145 return stmt 

146 

147 

148def _is_one_of(column: Any, values: list[Any]) -> sqlalchemy.ColumnElement[bool]: 

149 """``column IN (values)``. SQL's ``IN`` never matches NULL, so ``None`` 

150 among the values adds ``OR column IS NULL``, as a single ``null`` finds 

151 the rows without a value.""" 

152 present = [value for value in values if value is not None] 

153 if len(present) == len(values): 

154 return column.in_(values) 

155 if not present: 

156 return column.is_(None) 

157 return sqlalchemy.or_(column.in_(present), column.is_(None)) 

158 

159 

160def _apply_react_admin_sort_and_range( 

161 stmt: sqlalchemy.Select, 

162 model: type[Any], 

163 schema_cls: Any, 

164 sort: tuple[str, str] | None, 

165 start: int, 

166 end: int, 

167 sort_nulls: SortNulls = "last", 

168) -> sqlalchemy.Select: 

169 """The sort and the range (limit/offset) of a react-admin list.""" 

170 sorted_on = [] 

171 if sort: 

172 field, direction = sort 

173 key = SortKey(model, schema_cls, field) 

174 stmt = stmt.order_by( 

175 key.term(descending=direction == "DESC", sort_nulls=sort_nulls) 

176 ) 

177 sorted_on.append(key.column) 

178 stmt = order_by_primary_key(stmt, model, sorted_on=sorted_on) 

179 

180 return stmt.limit(end - start + 1).offset(start) 

181 

182 

183def _check_pagination(cls: type) -> None: 

184 """React-admin pages with ``range`` and reports the total in the 

185 ``Content-Range`` header. So a react-admin view needs the count of a 

186 ``NumberedPagination``, and uses only its two page sizes.""" 

187 # Disabling the count would report a total of 0 and silently break the 

188 # client's paging. 

189 pagination = getattr(cls, "pagination", None) 

190 if not isinstance(pagination, NumberedPagination): 

191 raise RestlyConfigurationError( 

192 f"{cls.__name__}: a react-admin view pages with the 'range' " 

193 "parameter, so 'pagination' must stay a fr.NumberedPagination. " 

194 "Restly reads its two page sizes, and counts the total for the " 

195 "Content-Range header." 

196 ) 

197 # any other setting would be silently ignored 

198 defaults = NumberedPagination() 

199 ignored = [ 

200 name 

201 for name in _UNUSED_PAGINATION_SETTINGS 

202 if getattr(pagination, name) != getattr(defaults, name) 

203 ] 

204 if ignored: 

205 raise RestlyConfigurationError( 

206 f"{cls.__name__}: a react-admin view uses only " 

207 "pagination.default_page_size and max_page_size. It pages with " 

208 "the 'range' parameter and reports the total in the " 

209 "Content-Range header, so these settings do not apply: " 

210 f"{', '.join(ignored)}." 

211 ) 

212 

213 

214def _check_list_params(cls: type) -> None: 

215 """The view reads the parsed ``sort``, ``range`` and ``filter`` from its 

216 list params, so they must be a ``ReactAdminListParams``.""" 

217 list_params = getattr(cls, "list_params_schema", None) 

218 if not ( 

219 isinstance(list_params, type) and issubclass(list_params, ReactAdminListParams) 

220 ): 

221 raise RestlyConfigurationError( 

222 f"{cls.__name__}.list_params_schema is {list_params!r}. A react-admin " 

223 "view reads sort, range and filter from its list params, so they " 

224 "must be a subclass of fr.views.ReactAdminListParams. To add a " 

225 "query key, subclass ReactAdminListParams." 

226 ) 

227 

228 

229def _check_list_response(cls: Any) -> None: 

230 """The view sends a JSON array. A view that replaces the endpoint or 

231 :meth:`to_list_response` can send anything else.""" 

232 if cls.to_list_response is not _ReactAdminMixin.to_list_response: 

233 return 

234 endpoint = cls.get_many_endpoint 

235 if endpoint is None or not endpoint.__module__.startswith("fastapi_restly."): 

236 return 

237 list_response = cls.list_response_schema 

238 if get_origin(list_response) is not list: 

239 raise RestlyConfigurationError( 

240 f"{cls.__name__}.list_response_schema is {list_response!r}. A " 

241 "react-admin list is a JSON array, so it must be a list type, such " 

242 "as list[UserSummary]. For another shape, replace get_many_endpoint." 

243 ) 

244 

245 

246def _reject_list_settings(cls: type) -> None: 

247 """React-admin sends its filters and sort order in its own parameters. 

248 So a list setting other than the default, or a filter method, would be 

249 silently ignored.""" 

250 # A view that inherits a setting sets the default again, to show it knows. 

251 for name in _LIST_SETTINGS: 

252 default = getattr(BaseRestView, name) 

253 if _list_setting(cls, name) == default: 

254 continue 

255 if _owner(cls, name) is cls: 

256 fix = "Remove the setting." 

257 else: 

258 fix = f"Set {name} = {default!r} on {cls.__name__}." 

259 raise RestlyConfigurationError( 

260 f"{cls.__name__} {_how_set(cls, name)}, which a react-admin " 

261 "view does not use. React-admin sends its filters and sort " 

262 f"order in the 'filter' and 'sort' parameters, as JSON. {fix}" 

263 ) 

264 for name in _list_filter_methods(cls): 

265 raise RestlyConfigurationError( 

266 f"{cls.__name__}.{name}{_set_by(cls, name)} has " 

267 "@fr.list_filter, which a react-admin view does not use. " 

268 "React-admin sends its filters in the 'filter' parameter, as " 

269 "JSON. Override apply_filters to read another filter." 

270 ) 

271 

272 

273# --------------------------------------------------------------------------- 

274# Shared implementation mixin 

275# --------------------------------------------------------------------------- 

276 

277 

278class _ReactAdminViewProtocol(Protocol): 

279 model: ClassVar[type[Any]] 

280 response_schema: ClassVar[type[pydantic.BaseModel]] 

281 update_schema: ClassVar[type[pydantic.BaseModel]] 

282 pagination: ClassVar[Pagination | None] 

283 sort_nulls: ClassVar[SortNulls] 

284 put: ClassVar[Any] 

285 

286 def get_react_admin_range_unit(self) -> str: ... 

287 

288 

289class _ReactAdminMixin: 

290 """ 

291 Shared transport helpers for react-admin views. 

292 

293 This is an implementation detail shared by ReactAdminView and 

294 AsyncReactAdminView. User-facing customization should happen by 

295 subclassing one of those concrete view classes. 

296 

297 Set ``pagination = fr.NumberedPagination(default_page_size=...)`` on a 

298 subclass to change the implicit page size used when the client does not 

299 send a ``range`` query parameter. Its ``max_page_size`` caps the rows one 

300 ``range`` asks for. The other pagination settings do not apply: 

301 react-admin pages with ``range`` and reports the total in the 

302 ``Content-Range`` header. 

303 

304 Type annotations on the mixin methods use ``_ReactAdminViewProtocol`` to 

305 make the expected ``RestView`` surface explicit to static checkers. 

306 """ 

307 

308 #: Only ``default_page_size`` and ``max_page_size`` apply: the implicit 

309 #: page size when no ``range`` parameter is sent, and the most rows one 

310 #: ``range`` may ask for. Override per view. 

311 pagination: ClassVar[Pagination | None] = NumberedPagination( 

312 default_page_size=DEFAULT_REACT_ADMIN_PAGE_SIZE 

313 ) 

314 

315 list_params_schema: ClassVar[type[pydantic.BaseModel]] = ReactAdminListParams 

316 

317 #: A react-admin list is a JSON array, without an envelope. 

318 list_response_schema: ClassVar[Any] = SchemaType( 

319 lambda view: list[view.response_schema] 

320 ) 

321 

322 _list_adapter: ClassVar[Any] = SchemaType( 

323 lambda view: pydantic.TypeAdapter(view.list_response_schema) 

324 ) 

325 

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

327 # A class that inherits list params of its own gets generated list 

328 # params when it sets a schema or a model. So each class declares 

329 # the list params that it inherits again, before Restly looks at them. 

330 if "list_params_schema" not in cls.__dict__: 

331 inherited = inspect.getattr_static(cls, "list_params_schema") 

332 setattr(cls, "list_params_schema", inherited) 

333 super().__init_subclass__(**kwargs) 

334 _check_pagination(cls) 

335 # A function gets its turn at registration: it can read what is not 

336 # there yet. 

337 if not isinstance(vars(cls)["list_params_schema"], SchemaType): 

338 _check_list_params(cls) 

339 

340 def get_react_admin_range_unit(self) -> str: 

341 """Return the unit string used in the Content-Range header.""" 

342 return "items" 

343 

344 def _react_admin_list_params(self, list_params: Any) -> Any: 

345 """``list_params`` as an instance of the view's list params. 

346 

347 A ``QueryParams`` or a mapping holds query values, so it is checked 

348 as on the list route. No public form yet. 

349 """ 

350 return cast(Any, self)._validated_list_params(list_params) 

351 

352 def _react_admin_range(self, list_params: Any) -> tuple[int, int]: 

353 """The first and the last row of ``range``, or of the first page 

354 when the client sends no ``range``. 

355 

356 :raises RequestValidationError: the range asks for more rows than 

357 ``pagination.max_page_size``. 

358 """ 

359 # ``pagination`` is a NumberedPagination on react-admin (see 

360 # _check_pagination). 

361 pagination = cast( 

362 NumberedPagination, cast(_ReactAdminViewProtocol, self).pagination 

363 ) 

364 row_range = getattr(list_params, "range", None) 

365 if row_range is None: 

366 return 0, pagination.default_page_size - 1 

367 start, end = row_range 

368 if end - start + 1 > pagination.max_page_size: 

369 raise RequestValidationError( 

370 [ 

371 { 

372 "type": "value_error", 

373 "loc": ("query", "range"), 

374 "msg": ( 

375 "Value error, a range can ask for at most " 

376 f"{pagination.max_page_size} rows" 

377 ), 

378 "input": [start, end], 

379 } 

380 ] 

381 ) 

382 return start, end 

383 

384 def _react_admin_filters( 

385 self, stmt: sqlalchemy.Select, list_params: Any 

386 ) -> sqlalchemy.Select: 

387 view = cast(_ReactAdminViewProtocol, self) 

388 params = self._react_admin_list_params(list_params) 

389 filters = getattr(params, "filter", None) or {} 

390 return _apply_react_admin_filters( 

391 stmt, view.model, view.response_schema, filters 

392 ) 

393 

394 def _react_admin_sort_and_range( 

395 self, stmt: sqlalchemy.Select, list_params: Any 

396 ) -> sqlalchemy.Select: 

397 view = cast(_ReactAdminViewProtocol, self) 

398 params = self._react_admin_list_params(list_params) 

399 start, end = self._react_admin_range(params) 

400 return _apply_react_admin_sort_and_range( 

401 stmt, 

402 view.model, 

403 view.response_schema, 

404 getattr(params, "sort", None), 

405 start, 

406 end, 

407 view.sort_nulls, 

408 ) 

409 

410 def to_list_response(self, list_result: ListResult[Any]) -> fastapi.Response: 

411 """Build the react-admin list response: a JSON array with a 

412 ``Content-Range`` header.""" 

413 # The items of the list response read the fields that they name from 

414 # what to_single_response returns, by field name and in lax mode, as the 

415 # other responses do. 

416 adapter = type(self)._list_adapter 

417 rows = adapter.validate_python( 

418 [cast(Any, self).to_single_response(obj) for obj in list_result.objects], 

419 from_attributes=True, 

420 by_alias=False, 

421 by_name=True, 

422 strict=False, 

423 ) 

424 params = self._react_admin_list_params(list_result.list_params) 

425 start, _ = self._react_admin_range(params) 

426 view = cast(_ReactAdminViewProtocol, self) 

427 unit = view.get_react_admin_range_unit() 

428 last = start + len(rows) - 1 if rows else start 

429 total = list_result.total_count or 0 

430 # This response goes out as it is, so it sends the status of the route. 

431 _, route_kwargs = getattr( 

432 type(self).get_many_endpoint, "_api_route_args", ("", {}) 

433 ) 

434 return fastapi.Response( 

435 status_code=route_kwargs.get("status_code") or 200, 

436 # As the class writes it, as in the other responses: a NaN becomes 

437 # the text "NaN". json.dumps would write NaN without quotes, which 

438 # is not JSON. 

439 content=adapter.dump_json(rows, by_alias=True), 

440 media_type="application/json", 

441 headers={ 

442 "Content-Range": f"{unit} {start}-{last}/{total}", 

443 "Access-Control-Expose-Headers": "Content-Range", 

444 }, 

445 ) 

446 

447 @classmethod 

448 def before_include_view(cls) -> None: 

449 # At registration, as Restly checks these settings. No public form 

450 # yet. 

451 _reject_list_settings(cls) 

452 _check_list_params(cls) 

453 _check_list_response(cls) 

454 cast(Any, super()).before_include_view() 

455 

456 

457# --------------------------------------------------------------------------- 

458# Concrete view classes 

459# --------------------------------------------------------------------------- 

460 

461 

462class AsyncReactAdminView(_ReactAdminMixin, AsyncRestView): 

463 """ 

464 AsyncRestView that follows the ra-data-simple-rest HTTP contract. 

465 

466 Use this instead of AsyncRestView when your frontend is react-admin 

467 with ra-data-simple-rest. 

468 """ 

469 

470 # A class's own routes come first, so this keeps GET / first in OpenAPI. 

471 @get("/") 

472 async def get_many_endpoint(self, list_params: Any) -> ViewListResponse: 

473 return await self.handle_get_many(list_params) 

474 

475 async def apply_list_params( 

476 self, stmt: sqlalchemy.Select, list_params: Any 

477 ) -> sqlalchemy.Select: 

478 """Apply the react-admin list params to the scoped base statement: 

479 :meth:`apply_filters`, then ``sort`` and ``range``.""" 

480 stmt = await self.apply_filters(stmt, list_params) 

481 return self._react_admin_sort_and_range(stmt, list_params) 

482 

483 async def apply_filters( 

484 self, stmt: sqlalchemy.Select, list_params: Any 

485 ) -> sqlalchemy.Select: 

486 """Apply the react-admin ``filter`` to ``stmt``, without the sort and 

487 the range.""" 

488 return self._react_admin_filters(stmt, list_params) 

489 

490 @put("/{id}") 

491 async def put(self, id: IDType, data: ViewUpdate) -> ViewResponse: 

492 """``PUT /{id}`` endpoint method, for react-admin's ``update``. It 

493 runs the same steps as ``PATCH``: 

494 :meth:`~fastapi_restly.views.AsyncRestView.handle_update`, with the 

495 view's ``update_schema`` body. An ``update`` override changes both 

496 routes. Replace this method to give ``PUT`` its own rules; see 

497 :ref:`react-admin-put`.""" 

498 return await self.handle_update(id, data) 

499 

500 

501class ReactAdminView(_ReactAdminMixin, RestView): 

502 """ 

503 RestView that follows the ra-data-simple-rest HTTP contract. 

504 

505 Use this instead of RestView when your frontend is react-admin 

506 with ra-data-simple-rest. 

507 """ 

508 

509 # A class's own routes come first, so this keeps GET / first in OpenAPI. 

510 @get("/") 

511 def get_many_endpoint(self, list_params: Any) -> ViewListResponse: 

512 return self.handle_get_many(list_params) 

513 

514 def apply_list_params( 

515 self, stmt: sqlalchemy.Select, list_params: Any 

516 ) -> sqlalchemy.Select: 

517 """Apply the react-admin list params to the scoped base statement: 

518 :meth:`apply_filters`, then ``sort`` and ``range``.""" 

519 stmt = self.apply_filters(stmt, list_params) 

520 return self._react_admin_sort_and_range(stmt, list_params) 

521 

522 def apply_filters( 

523 self, stmt: sqlalchemy.Select, list_params: Any 

524 ) -> sqlalchemy.Select: 

525 """Apply the react-admin ``filter`` to ``stmt``, without the sort and 

526 the range.""" 

527 return self._react_admin_filters(stmt, list_params) 

528 

529 @put("/{id}") 

530 def put(self, id: IDType, data: ViewUpdate) -> ViewResponse: 

531 """``PUT /{id}`` endpoint method, for react-admin's ``update``. It 

532 runs the same steps as ``PATCH``: 

533 :meth:`~fastapi_restly.views.RestView.handle_update`, with the view's 

534 ``update_schema`` body. An ``update`` override changes both routes. 

535 Replace this method to give ``PUT`` its own rules; see 

536 :ref:`react-admin-put`.""" 

537 return self.handle_update(id, data)