-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathquery.py
More file actions
90 lines (82 loc) · 2.53 KB
/
query.py
File metadata and controls
90 lines (82 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
"""REST API query utilities."""
from __future__ import annotations
import json
import typing as t
import pydantic as pdt
from fastapi import HTTPException, Query
class QueryParams(pdt.BaseModel):
filters: dict[str, t.Any] = pdt.Field(
default_factory=dict,
description='AiiDA QueryBuilder filters',
examples=[
{'node_type': {'==': 'data.core.int.Int.'}},
{'attributes.value': {'>': 42}},
],
)
order_by: str | list[str] | dict[str, t.Any] | None = pdt.Field(
None,
description='Fields to sort by',
examples=[
{'attributes.value': 'desc'},
],
)
page_size: pdt.PositiveInt = pdt.Field(
10,
description='Number of results per page',
examples=[10],
)
page: pdt.PositiveInt = pdt.Field(
1,
description='Page number',
examples=[1],
)
def query_params(
filters: str | None = Query(
None,
description='AiiDA QueryBuilder filters as JSON string',
),
order_by: str | None = Query(
None,
description='Comma-separated list of fields to sort by',
),
page_size: pdt.PositiveInt = Query(
10,
description='Number of results per page',
),
page: pdt.PositiveInt = Query(
1,
description='Page number',
),
) -> QueryParams:
"""Parse query parameters into a structured object.
:param filters: AiiDA QueryBuilder filters as JSON string.
:param order_by: Comma-separated string of fields to sort by.
:param page_size: Number of results per page.
:param page: Page number.
:return: Structured query parameters.
:raises HTTPException: If filters cannot be parsed as JSON.
"""
query_filters: dict[str, t.Any] = {}
query_order_by: str | list[str] | dict[str, t.Any] | None = None
if filters:
try:
query_filters = json.loads(filters)
except Exception as exception:
raise HTTPException(
status_code=400,
detail=f'Could not parse filters as JSON: {exception}',
) from exception
if order_by:
try:
query_order_by = json.loads(order_by)
except Exception as exception:
raise HTTPException(
status_code=400,
detail=f'Could not parse order_by as JSON: {exception}',
) from exception
return QueryParams(
filters=query_filters,
order_by=query_order_by,
page_size=page_size,
page=page,
)