You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "pierrejeambrun (via GitHub)" <gi...@apache.org> on 2024/09/18 14:37:20 UTC
[PR] FastAPI API Add test query params standardization an reusability [airflow]
pierrejeambrun opened a new pull request, #42320:
URL: https://github.com/apache/airflow/pull/42320
This will abstract the handling of common FIlters, Search and Sort query param so we do not have to copy and past the same `query.where(...)` on all endpoints that are using this same logic.
This allows:
- To remove some logic from the views, and only keep http related thing. (serialization/deserialization, query param validation, etc...)
- Initialize some reusable logic for the db layer
- Will allow to add more complex filters that cannot be done today, especially on the `order_by` because we were using a `text` clause that do not work with hybrid properties. (cf follow up PR to add ordering by `dag_display_name`)
The goal is to have that extended and have a library of `query params` that can be re-used accross all the RestAPI.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1771038111
##########
airflow/api_fastapi/parameters.py:
##########
@@ -0,0 +1,165 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import Any, Generic, List, TypeVar, Union
+
+from fastapi import Depends, HTTPException, Query as Query
+from sqlalchemy import or_
+from sqlalchemy.sql import ColumnElement, Select
+from typing_extensions import Annotated, Self
+
+from airflow.models.dag import DagModel, DagTag
+
+T = TypeVar("T")
+
+
+class BaseParam(Generic[T], ABC):
+ """Base class for filters."""
+
+ def __init__(self) -> None:
+ self.value: T | None = None
+ self.attribute: ColumnElement | None = None
+
+ @abstractmethod
+ def to_orm(self, select: Select) -> Select:
+ pass
+
+ @abstractmethod
+ def __call__(self, *args: Any, **kwarg: Any) -> BaseParam:
+ pass
+
+ def set_value(self, value: T) -> Self:
+ self.value = value
+ return self
+
+
+class _LimitFilter(BaseParam[int]):
+ """Filter on the limit."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+
+ return select.limit(self.value)
+
+ def __call__(self, limit: int = 100) -> _LimitFilter:
+ self.value = limit
+
+ return self
+
+
+class _OffsetFilter(BaseParam[int]):
+ """Filter on offset."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.offset(self.value)
+
+ def __call__(self, offset: int = 0) -> _OffsetFilter:
+ self.value = offset
+
+ return self
Review Comment:
Done thanks, also updated at other places
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1771037509
##########
airflow/api_fastapi/parameters.py:
##########
@@ -0,0 +1,165 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import Any, Generic, List, TypeVar, Union
+
+from fastapi import Depends, HTTPException, Query as Query
+from sqlalchemy import or_
+from sqlalchemy.sql import ColumnElement, Select
+from typing_extensions import Annotated, Self
+
+from airflow.models.dag import DagModel, DagTag
+
+T = TypeVar("T")
+
+
+class BaseParam(Generic[T], ABC):
+ """Base class for filters."""
+
+ def __init__(self) -> None:
+ self.value: T | None = None
+ self.attribute: ColumnElement | None = None
+
+ @abstractmethod
+ def to_orm(self, select: Select) -> Select:
+ pass
+
+ @abstractmethod
+ def __call__(self, *args: Any, **kwarg: Any) -> BaseParam:
+ pass
+
+ def set_value(self, value: T) -> Self:
+ self.value = value
+ return self
+
+
+class _LimitFilter(BaseParam[int]):
+ """Filter on the limit."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+
+ return select.limit(self.value)
+
+ def __call__(self, limit: int = 100) -> _LimitFilter:
+ self.value = limit
+
+ return self
Review Comment:
Updated at other places as well. Thanks.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "jedcunningham (via GitHub)" <gi...@apache.org>.
jedcunningham commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1768955752
##########
airflow/api_fastapi/parameters.py:
##########
@@ -0,0 +1,165 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import Any, Generic, List, TypeVar, Union
+
+from fastapi import Depends, HTTPException, Query as Query
+from sqlalchemy import or_
+from sqlalchemy.sql import ColumnElement, Select
+from typing_extensions import Annotated, Self
+
+from airflow.models.dag import DagModel, DagTag
+
+T = TypeVar("T")
+
+
+class BaseParam(Generic[T], ABC):
+ """Base class for filters."""
+
+ def __init__(self) -> None:
+ self.value: T | None = None
+ self.attribute: ColumnElement | None = None
+
+ @abstractmethod
+ def to_orm(self, select: Select) -> Select:
+ pass
+
+ @abstractmethod
+ def __call__(self, *args: Any, **kwarg: Any) -> BaseParam:
+ pass
+
+ def set_value(self, value: T) -> Self:
+ self.value = value
+ return self
+
+
+class _LimitFilter(BaseParam[int]):
+ """Filter on the limit."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+
+ return select.limit(self.value)
+
+ def __call__(self, limit: int = 100) -> _LimitFilter:
+ self.value = limit
+
+ return self
+
+
+class _OffsetFilter(BaseParam[int]):
+ """Filter on offset."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.offset(self.value)
+
+ def __call__(self, offset: int = 0) -> _OffsetFilter:
+ self.value = offset
+
+ return self
Review Comment:
```suggestion
return self.set_value(offset)
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "jedcunningham (via GitHub)" <gi...@apache.org>.
jedcunningham commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1768933589
##########
airflow/api_fastapi/parameters.py:
##########
@@ -0,0 +1,165 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import Any, Generic, List, TypeVar, Union
+
+from fastapi import Depends, HTTPException, Query as Query
+from sqlalchemy import or_
+from sqlalchemy.sql import ColumnElement, Select
+from typing_extensions import Annotated, Self
+
+from airflow.models.dag import DagModel, DagTag
+
+T = TypeVar("T")
+
+
+class BaseParam(Generic[T], ABC):
+ """Base class for filters."""
+
+ def __init__(self) -> None:
+ self.value: T | None = None
+ self.attribute: ColumnElement | None = None
+
+ @abstractmethod
+ def to_orm(self, select: Select) -> Select:
+ pass
+
+ @abstractmethod
+ def __call__(self, *args: Any, **kwarg: Any) -> BaseParam:
+ pass
+
+ def set_value(self, value: T) -> Self:
+ self.value = value
+ return self
+
+
+class _LimitFilter(BaseParam[int]):
+ """Filter on the limit."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+
+ return select.limit(self.value)
+
+ def __call__(self, limit: int = 100) -> _LimitFilter:
+ self.value = limit
+
+ return self
+
+
+class _OffsetFilter(BaseParam[int]):
+ """Filter on offset."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.offset(self.value)
+
+ def __call__(self, offset: int = 0) -> _OffsetFilter:
+ self.value = offset
+
+ return self
+
+
+class _PausedFilter(BaseParam[Union[bool, None]]):
+ """Filter on is_paused."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.where(DagModel.is_paused == self.value)
+
+ def __call__(self, paused: bool | None = Query(default=None)) -> _PausedFilter:
+ return self.set_value(paused)
+
+
+class _OnlyActiveFilter(BaseParam[bool]):
+ """Filter on is_active."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value:
+ return select.where(DagModel.is_active == self.value)
+ return select
+
+ def __call__(self, only_active: bool = Query(default=True)) -> _OnlyActiveFilter:
+ return self.set_value(only_active)
+
+
+class _DagIdPatternSearch(BaseParam[Union[str, None]]):
+ """Search on dag_id."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.where(DagModel.dag_id.ilike(f"%{self.value}"))
+
+ def __call__(self, dag_id_pattern: str | None = Query(default=None)) -> _DagIdPatternSearch:
+ return self.set_value(dag_id_pattern)
+
+
+class SortParam(BaseParam[Union[str]]):
+ """Order result by the attribute."""
+
+ def __init__(self, allowed_attrs: list[str]) -> None:
+ super().__init__()
+ self.allowed_attrs = allowed_attrs
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+
+ lstriped_orderby = self.value.lstrip("-")
+ if self.allowed_attrs and lstriped_orderby not in self.allowed_attrs:
+ raise HTTPException(
+ 400,
+ f"Ordering with '{lstriped_orderby}' is disallowed or "
+ f"the attribute does not exist on the model",
+ )
+ if self.value[0] == "-":
+ return select.order_by(getattr(DagModel, lstriped_orderby).desc())
+ else:
+ return select.order_by(getattr(DagModel, lstriped_orderby).asc())
+ return select
Review Comment:
```suggestion
```
This will never be hit, the else will.
##########
airflow/api_fastapi/parameters.py:
##########
@@ -0,0 +1,165 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import Any, Generic, List, TypeVar, Union
+
+from fastapi import Depends, HTTPException, Query as Query
+from sqlalchemy import or_
+from sqlalchemy.sql import ColumnElement, Select
+from typing_extensions import Annotated, Self
+
+from airflow.models.dag import DagModel, DagTag
+
+T = TypeVar("T")
+
+
+class BaseParam(Generic[T], ABC):
+ """Base class for filters."""
+
+ def __init__(self) -> None:
+ self.value: T | None = None
+ self.attribute: ColumnElement | None = None
+
+ @abstractmethod
+ def to_orm(self, select: Select) -> Select:
+ pass
+
+ @abstractmethod
+ def __call__(self, *args: Any, **kwarg: Any) -> BaseParam:
+ pass
+
+ def set_value(self, value: T) -> Self:
+ self.value = value
+ return self
+
+
+class _LimitFilter(BaseParam[int]):
+ """Filter on the limit."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+
+ return select.limit(self.value)
+
+ def __call__(self, limit: int = 100) -> _LimitFilter:
+ self.value = limit
+
+ return self
+
+
+class _OffsetFilter(BaseParam[int]):
+ """Filter on offset."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.offset(self.value)
+
+ def __call__(self, offset: int = 0) -> _OffsetFilter:
+ self.value = offset
+
+ return self
+
+
+class _PausedFilter(BaseParam[Union[bool, None]]):
+ """Filter on is_paused."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.where(DagModel.is_paused == self.value)
+
+ def __call__(self, paused: bool | None = Query(default=None)) -> _PausedFilter:
+ return self.set_value(paused)
+
+
+class _OnlyActiveFilter(BaseParam[bool]):
+ """Filter on is_active."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value:
+ return select.where(DagModel.is_active == self.value)
+ return select
+
+ def __call__(self, only_active: bool = Query(default=True)) -> _OnlyActiveFilter:
+ return self.set_value(only_active)
+
+
+class _DagIdPatternSearch(BaseParam[Union[str, None]]):
+ """Search on dag_id."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.where(DagModel.dag_id.ilike(f"%{self.value}"))
+
+ def __call__(self, dag_id_pattern: str | None = Query(default=None)) -> _DagIdPatternSearch:
+ return self.set_value(dag_id_pattern)
+
+
+class SortParam(BaseParam[Union[str]]):
+ """Order result by the attribute."""
+
+ def __init__(self, allowed_attrs: list[str]) -> None:
+ super().__init__()
+ self.allowed_attrs = allowed_attrs
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+
+ lstriped_orderby = self.value.lstrip("-")
+ if self.allowed_attrs and lstriped_orderby not in self.allowed_attrs:
+ raise HTTPException(
+ 400,
+ f"Ordering with '{lstriped_orderby}' is disallowed or "
+ f"the attribute does not exist on the model",
+ )
+ if self.value[0] == "-":
+ return select.order_by(getattr(DagModel, lstriped_orderby).desc())
+ else:
+ return select.order_by(getattr(DagModel, lstriped_orderby).asc())
+ return select
+
+ def __call__(self, order_by: str = Query(default="dag_id")) -> SortParam:
+ return self.set_value(order_by)
+
+
+class _TagsFilter(BaseParam[List[str]]):
+ """Filter on tags."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value:
+ conditions = [DagModel.tags.any(DagTag.name == tag) for tag in self.value]
+ return select.where(or_(*conditions))
+
+ return select
Review Comment:
```suggestion
if self.value is None:
return select
conditions = [DagModel.tags.any(DagTag.name == tag) for tag in self.value]
return select.where(or_(*conditions))
```
Keep it consistent with the others, plus short circuiting out is easier to read imo.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1768677888
##########
airflow/api_fastapi/views/public/dags.py:
##########
@@ -35,39 +42,29 @@
@dags_router.get("/dags")
async def get_dags(
*,
- limit: int = 100,
- offset: int = 0,
- tags: Annotated[list[str] | None, Query()] = None,
- dag_id_pattern: str | None = None,
- only_active: bool = True,
- paused: bool | None = None,
- order_by: str = "dag_id",
+ limit: QueryLimit,
+ offset: QueryOffset,
+ tags: QueryTagsFilter,
+ dag_id_pattern: QueryDagIdPatternSearch,
+ only_active: QueryOnlyActiveFilter,
+ paused: QueryPausedFilter,
+ order_by: Annotated[SortParam, Depends(SortParam(["dag_id"]))],
session: Annotated[Session, Depends(get_session)],
) -> DAGCollectionResponse:
"""Get all DAGs."""
- allowed_sorting_attrs = ["dag_id"]
dags_query = select(DagModel)
- if only_active:
- dags_query = dags_query.where(DagModel.is_active)
- if paused is not None:
- if paused:
- dags_query = dags_query.where(DagModel.is_paused)
- else:
- dags_query = dags_query.where(~DagModel.is_paused)
- if dag_id_pattern:
- dags_query = dags_query.where(DagModel.dag_id.ilike(f"%{dag_id_pattern}%"))
+
+ dags_query = apply_filters_to_query(dags_query, [only_active, paused, dag_id_pattern, tags])
# TODO: Re-enable when permissions are handled.
# readable_dags = get_auth_manager().get_permitted_dag_ids(user=g.user)
# dags_query = dags_query.where(DagModel.dag_id.in_(readable_dags))
- if tags:
- cond = [DagModel.tags.any(DagTag.name == tag) for tag in tags]
- dags_query = dags_query.where(or_(*cond))
-
total_entries = get_query_count(dags_query, session=session)
- dags_query = apply_sorting(dags_query, order_by, {}, allowed_sorting_attrs)
- dags = session.scalars(dags_query.offset(offset).limit(limit)).all()
+
+ dags_query = apply_filters_to_query(dags_query, [order_by, offset, limit])
+
+ dags = session.scalars(dags_query).all()
Review Comment:
Done, that's even better becuase I do not have a name conflict between `sqlalchemy.sql.Query` and `fastapi.Query`, I don't have to alias anymore.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1771049009
##########
airflow/api_fastapi/parameters.py:
##########
@@ -0,0 +1,165 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import Any, Generic, List, TypeVar, Union
+
+from fastapi import Depends, HTTPException, Query as Query
+from sqlalchemy import or_
+from sqlalchemy.sql import ColumnElement, Select
+from typing_extensions import Annotated, Self
+
+from airflow.models.dag import DagModel, DagTag
+
+T = TypeVar("T")
+
+
+class BaseParam(Generic[T], ABC):
+ """Base class for filters."""
+
+ def __init__(self) -> None:
+ self.value: T | None = None
+ self.attribute: ColumnElement | None = None
+
+ @abstractmethod
+ def to_orm(self, select: Select) -> Select:
+ pass
+
+ @abstractmethod
+ def __call__(self, *args: Any, **kwarg: Any) -> BaseParam:
+ pass
+
+ def set_value(self, value: T) -> Self:
+ self.value = value
+ return self
+
+
+class _LimitFilter(BaseParam[int]):
+ """Filter on the limit."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+
+ return select.limit(self.value)
+
+ def __call__(self, limit: int = 100) -> _LimitFilter:
+ self.value = limit
+
+ return self
+
+
+class _OffsetFilter(BaseParam[int]):
+ """Filter on offset."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.offset(self.value)
+
+ def __call__(self, offset: int = 0) -> _OffsetFilter:
+ self.value = offset
+
+ return self
+
+
+class _PausedFilter(BaseParam[Union[bool, None]]):
+ """Filter on is_paused."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.where(DagModel.is_paused == self.value)
+
+ def __call__(self, paused: bool | None = Query(default=None)) -> _PausedFilter:
+ return self.set_value(paused)
+
+
+class _OnlyActiveFilter(BaseParam[bool]):
+ """Filter on is_active."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value:
+ return select.where(DagModel.is_active == self.value)
+ return select
+
+ def __call__(self, only_active: bool = Query(default=True)) -> _OnlyActiveFilter:
+ return self.set_value(only_active)
+
+
+class _DagIdPatternSearch(BaseParam[Union[str, None]]):
+ """Search on dag_id."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.where(DagModel.dag_id.ilike(f"%{self.value}"))
+
+ def __call__(self, dag_id_pattern: str | None = Query(default=None)) -> _DagIdPatternSearch:
+ return self.set_value(dag_id_pattern)
+
+
+class SortParam(BaseParam[Union[str]]):
+ """Order result by the attribute."""
+
+ def __init__(self, allowed_attrs: list[str]) -> None:
+ super().__init__()
+ self.allowed_attrs = allowed_attrs
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+
+ lstriped_orderby = self.value.lstrip("-")
+ if self.allowed_attrs and lstriped_orderby not in self.allowed_attrs:
+ raise HTTPException(
+ 400,
+ f"Ordering with '{lstriped_orderby}' is disallowed or "
+ f"the attribute does not exist on the model",
+ )
+ if self.value[0] == "-":
+ return select.order_by(getattr(DagModel, lstriped_orderby).desc())
+ else:
+ return select.order_by(getattr(DagModel, lstriped_orderby).asc())
+ return select
Review Comment:
Yes, the last return was useless, it was copy pasted from `api_connexion` and wasn't great. I updated both should look better now. Thanks.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1771066684
##########
airflow/api_fastapi/db.py:
##########
@@ -19,6 +19,9 @@
from typing import TYPE_CHECKING
+from sqlalchemy.sql import Select
+
+from airflow.api_fastapi.parameters import BaseParam
Review Comment:
"TCH001" and "TCH002" are disabled on `api_fastapi` folder. Same reason as for `serialization/pydantic/` pydantic manipulates annotations at runtime and this things will fail.
Also fails to detect `Annotated[type, ...]` depends as required at runtime. Moving things to such codeblock will fail. I don't think theres really a better workaround considering our constraints:
- We need `from future import __annotation__` in the file
- We want to support python 3.8 and 3.9
I moved to type checking block those that are not throwing errors.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "ephraimbuddy (via GitHub)" <gi...@apache.org>.
ephraimbuddy commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1768443794
##########
airflow/api_fastapi/views/public/dags.py:
##########
@@ -35,39 +42,29 @@
@dags_router.get("/dags")
async def get_dags(
*,
- limit: int = 100,
- offset: int = 0,
- tags: Annotated[list[str] | None, Query()] = None,
- dag_id_pattern: str | None = None,
- only_active: bool = True,
- paused: bool | None = None,
- order_by: str = "dag_id",
+ limit: QueryLimit,
+ offset: QueryOffset,
+ tags: QueryTagsFilter,
+ dag_id_pattern: QueryDagIdPatternSearch,
+ only_active: QueryOnlyActiveFilter,
+ paused: QueryPausedFilter,
+ order_by: Annotated[SortParam, Depends(SortParam(["dag_id"]))],
session: Annotated[Session, Depends(get_session)],
) -> DAGCollectionResponse:
"""Get all DAGs."""
- allowed_sorting_attrs = ["dag_id"]
dags_query = select(DagModel)
- if only_active:
- dags_query = dags_query.where(DagModel.is_active)
- if paused is not None:
- if paused:
- dags_query = dags_query.where(DagModel.is_paused)
- else:
- dags_query = dags_query.where(~DagModel.is_paused)
- if dag_id_pattern:
- dags_query = dags_query.where(DagModel.dag_id.ilike(f"%{dag_id_pattern}%"))
+
+ dags_query = apply_filters_to_query(dags_query, [only_active, paused, dag_id_pattern, tags])
# TODO: Re-enable when permissions are handled.
# readable_dags = get_auth_manager().get_permitted_dag_ids(user=g.user)
# dags_query = dags_query.where(DagModel.dag_id.in_(readable_dags))
- if tags:
- cond = [DagModel.tags.any(DagTag.name == tag) for tag in tags]
- dags_query = dags_query.where(or_(*cond))
-
total_entries = get_query_count(dags_query, session=session)
- dags_query = apply_sorting(dags_query, order_by, {}, allowed_sorting_attrs)
- dags = session.scalars(dags_query.offset(offset).limit(limit)).all()
+
+ dags_query = apply_filters_to_query(dags_query, [order_by, offset, limit])
+
+ dags = session.scalars(dags_query).all()
Review Comment:
In sqlalchemy 2, which we are now using, query is no longer the right word; select is being used, and I think we should follow it since we are writing a new API. No strong opinion here, but when you look at sections like https://docs.sqlalchemy.org/en/20/orm/queryguide/select.html, you discover that the new term is select. If we are to use the select, then names like `dags_query`, `apply_filters_to_query` should be changed to `dags_select`, `apply_filters_to_select` etc. And looking at it, it's not until line 67 that we performed a query to the DB
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1768699784
##########
airflow/api_fastapi/views/public/dags.py:
##########
@@ -35,39 +42,29 @@
@dags_router.get("/dags")
async def get_dags(
*,
- limit: int = 100,
- offset: int = 0,
- tags: Annotated[list[str] | None, Query()] = None,
- dag_id_pattern: str | None = None,
- only_active: bool = True,
- paused: bool | None = None,
- order_by: str = "dag_id",
+ limit: QueryLimit,
+ offset: QueryOffset,
+ tags: QueryTagsFilter,
+ dag_id_pattern: QueryDagIdPatternSearch,
+ only_active: QueryOnlyActiveFilter,
+ paused: QueryPausedFilter,
+ order_by: Annotated[SortParam, Depends(SortParam(["dag_id"]))],
session: Annotated[Session, Depends(get_session)],
) -> DAGCollectionResponse:
"""Get all DAGs."""
- allowed_sorting_attrs = ["dag_id"]
dags_query = select(DagModel)
- if only_active:
- dags_query = dags_query.where(DagModel.is_active)
- if paused is not None:
- if paused:
- dags_query = dags_query.where(DagModel.is_paused)
- else:
- dags_query = dags_query.where(~DagModel.is_paused)
- if dag_id_pattern:
- dags_query = dags_query.where(DagModel.dag_id.ilike(f"%{dag_id_pattern}%"))
+
+ dags_query = apply_filters_to_query(dags_query, [only_active, paused, dag_id_pattern, tags])
# TODO: Re-enable when permissions are handled.
# readable_dags = get_auth_manager().get_permitted_dag_ids(user=g.user)
# dags_query = dags_query.where(DagModel.dag_id.in_(readable_dags))
- if tags:
- cond = [DagModel.tags.any(DagTag.name == tag) for tag in tags]
- dags_query = dags_query.where(or_(*cond))
-
total_entries = get_query_count(dags_query, session=session)
- dags_query = apply_sorting(dags_query, order_by, {}, allowed_sorting_attrs)
- dags = session.scalars(dags_query.offset(offset).limit(limit)).all()
+
+ dags_query = apply_filters_to_query(dags_query, [order_by, offset, limit])
+
+ dags = session.scalars(dags_query).all()
Review Comment:
Do you happen do have found a good documentation on SQLAlchemy internal types and how to type annotate sqlalchemy expressions (columns, selectables, filters, cte, etc...) I can't put my hand on that in their doc. I remember having the same issue with 1.x version. I mean some example of common use cases.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1768699784
##########
airflow/api_fastapi/views/public/dags.py:
##########
@@ -35,39 +42,29 @@
@dags_router.get("/dags")
async def get_dags(
*,
- limit: int = 100,
- offset: int = 0,
- tags: Annotated[list[str] | None, Query()] = None,
- dag_id_pattern: str | None = None,
- only_active: bool = True,
- paused: bool | None = None,
- order_by: str = "dag_id",
+ limit: QueryLimit,
+ offset: QueryOffset,
+ tags: QueryTagsFilter,
+ dag_id_pattern: QueryDagIdPatternSearch,
+ only_active: QueryOnlyActiveFilter,
+ paused: QueryPausedFilter,
+ order_by: Annotated[SortParam, Depends(SortParam(["dag_id"]))],
session: Annotated[Session, Depends(get_session)],
) -> DAGCollectionResponse:
"""Get all DAGs."""
- allowed_sorting_attrs = ["dag_id"]
dags_query = select(DagModel)
- if only_active:
- dags_query = dags_query.where(DagModel.is_active)
- if paused is not None:
- if paused:
- dags_query = dags_query.where(DagModel.is_paused)
- else:
- dags_query = dags_query.where(~DagModel.is_paused)
- if dag_id_pattern:
- dags_query = dags_query.where(DagModel.dag_id.ilike(f"%{dag_id_pattern}%"))
+
+ dags_query = apply_filters_to_query(dags_query, [only_active, paused, dag_id_pattern, tags])
# TODO: Re-enable when permissions are handled.
# readable_dags = get_auth_manager().get_permitted_dag_ids(user=g.user)
# dags_query = dags_query.where(DagModel.dag_id.in_(readable_dags))
- if tags:
- cond = [DagModel.tags.any(DagTag.name == tag) for tag in tags]
- dags_query = dags_query.where(or_(*cond))
-
total_entries = get_query_count(dags_query, session=session)
- dags_query = apply_sorting(dags_query, order_by, {}, allowed_sorting_attrs)
- dags = session.scalars(dags_query.offset(offset).limit(limit)).all()
+
+ dags_query = apply_filters_to_query(dags_query, [order_by, offset, limit])
+
+ dags = session.scalars(dags_query).all()
Review Comment:
Do you happen do have found a good documentation on SQLAlchemy internal types and how to type annotate sqlalchemy expressions (columns, selectables, filters, cte, etc...) I can't put my hand on that in their doc. I remember having the same issue with 1.x version. I mean some example of common use cases.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1771033848
##########
airflow/api_fastapi/parameters.py:
##########
@@ -0,0 +1,165 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import Any, Generic, List, TypeVar, Union
+
+from fastapi import Depends, HTTPException, Query as Query
+from sqlalchemy import or_
+from sqlalchemy.sql import ColumnElement, Select
+from typing_extensions import Annotated, Self
+
+from airflow.models.dag import DagModel, DagTag
+
+T = TypeVar("T")
+
+
+class BaseParam(Generic[T], ABC):
+ """Base class for filters."""
+
+ def __init__(self) -> None:
+ self.value: T | None = None
+ self.attribute: ColumnElement | None = None
+
+ @abstractmethod
+ def to_orm(self, select: Select) -> Select:
+ pass
+
+ @abstractmethod
+ def __call__(self, *args: Any, **kwarg: Any) -> BaseParam:
+ pass
+
+ def set_value(self, value: T) -> Self:
+ self.value = value
+ return self
+
+
+class _LimitFilter(BaseParam[int]):
+ """Filter on the limit."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+
+ return select.limit(self.value)
+
+ def __call__(self, limit: int = 100) -> _LimitFilter:
+ self.value = limit
+
+ return self
+
+
+class _OffsetFilter(BaseParam[int]):
+ """Filter on offset."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.offset(self.value)
+
+ def __call__(self, offset: int = 0) -> _OffsetFilter:
+ self.value = offset
+
+ return self
+
+
+class _PausedFilter(BaseParam[Union[bool, None]]):
+ """Filter on is_paused."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.where(DagModel.is_paused == self.value)
+
+ def __call__(self, paused: bool | None = Query(default=None)) -> _PausedFilter:
+ return self.set_value(paused)
+
+
+class _OnlyActiveFilter(BaseParam[bool]):
+ """Filter on is_active."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value:
+ return select.where(DagModel.is_active == self.value)
+ return select
+
+ def __call__(self, only_active: bool = Query(default=True)) -> _OnlyActiveFilter:
+ return self.set_value(only_active)
+
+
+class _DagIdPatternSearch(BaseParam[Union[str, None]]):
+ """Search on dag_id."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.where(DagModel.dag_id.ilike(f"%{self.value}"))
+
+ def __call__(self, dag_id_pattern: str | None = Query(default=None)) -> _DagIdPatternSearch:
+ return self.set_value(dag_id_pattern)
+
+
+class SortParam(BaseParam[Union[str]]):
+ """Order result by the attribute."""
+
+ def __init__(self, allowed_attrs: list[str]) -> None:
+ super().__init__()
+ self.allowed_attrs = allowed_attrs
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+
+ lstriped_orderby = self.value.lstrip("-")
+ if self.allowed_attrs and lstriped_orderby not in self.allowed_attrs:
+ raise HTTPException(
+ 400,
+ f"Ordering with '{lstriped_orderby}' is disallowed or "
+ f"the attribute does not exist on the model",
+ )
+ if self.value[0] == "-":
+ return select.order_by(getattr(DagModel, lstriped_orderby).desc())
+ else:
+ return select.order_by(getattr(DagModel, lstriped_orderby).asc())
+ return select
Review Comment:
Thanks. I naively copy/pasted this from `api_connexion/parameters`. Modified at both places.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1768677888
##########
airflow/api_fastapi/views/public/dags.py:
##########
@@ -35,39 +42,29 @@
@dags_router.get("/dags")
async def get_dags(
*,
- limit: int = 100,
- offset: int = 0,
- tags: Annotated[list[str] | None, Query()] = None,
- dag_id_pattern: str | None = None,
- only_active: bool = True,
- paused: bool | None = None,
- order_by: str = "dag_id",
+ limit: QueryLimit,
+ offset: QueryOffset,
+ tags: QueryTagsFilter,
+ dag_id_pattern: QueryDagIdPatternSearch,
+ only_active: QueryOnlyActiveFilter,
+ paused: QueryPausedFilter,
+ order_by: Annotated[SortParam, Depends(SortParam(["dag_id"]))],
session: Annotated[Session, Depends(get_session)],
) -> DAGCollectionResponse:
"""Get all DAGs."""
- allowed_sorting_attrs = ["dag_id"]
dags_query = select(DagModel)
- if only_active:
- dags_query = dags_query.where(DagModel.is_active)
- if paused is not None:
- if paused:
- dags_query = dags_query.where(DagModel.is_paused)
- else:
- dags_query = dags_query.where(~DagModel.is_paused)
- if dag_id_pattern:
- dags_query = dags_query.where(DagModel.dag_id.ilike(f"%{dag_id_pattern}%"))
+
+ dags_query = apply_filters_to_query(dags_query, [only_active, paused, dag_id_pattern, tags])
# TODO: Re-enable when permissions are handled.
# readable_dags = get_auth_manager().get_permitted_dag_ids(user=g.user)
# dags_query = dags_query.where(DagModel.dag_id.in_(readable_dags))
- if tags:
- cond = [DagModel.tags.any(DagTag.name == tag) for tag in tags]
- dags_query = dags_query.where(or_(*cond))
-
total_entries = get_query_count(dags_query, session=session)
- dags_query = apply_sorting(dags_query, order_by, {}, allowed_sorting_attrs)
- dags = session.scalars(dags_query.offset(offset).limit(limit)).all()
+
+ dags_query = apply_filters_to_query(dags_query, [order_by, offset, limit])
+
+ dags = session.scalars(dags_query).all()
Review Comment:
Done, that's even better because I do not have a name conflict between `sqlalchemy.sql.Query` and `fastapi.Query` anymore, I don't have to alias anymore.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1771066684
##########
airflow/api_fastapi/db.py:
##########
@@ -19,6 +19,9 @@
from typing import TYPE_CHECKING
+from sqlalchemy.sql import Select
+
+from airflow.api_fastapi.parameters import BaseParam
Review Comment:
"TCH001" and "TCH002" are disabled on `api_fastapi` folder. Same reason as for `serialization/pydantic/` pydantic manipulates annotations at runtime and this things will fail.
Also `Annotated` for old python version and future __annotations__ are not working well.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1768699784
##########
airflow/api_fastapi/views/public/dags.py:
##########
@@ -35,39 +42,29 @@
@dags_router.get("/dags")
async def get_dags(
*,
- limit: int = 100,
- offset: int = 0,
- tags: Annotated[list[str] | None, Query()] = None,
- dag_id_pattern: str | None = None,
- only_active: bool = True,
- paused: bool | None = None,
- order_by: str = "dag_id",
+ limit: QueryLimit,
+ offset: QueryOffset,
+ tags: QueryTagsFilter,
+ dag_id_pattern: QueryDagIdPatternSearch,
+ only_active: QueryOnlyActiveFilter,
+ paused: QueryPausedFilter,
+ order_by: Annotated[SortParam, Depends(SortParam(["dag_id"]))],
session: Annotated[Session, Depends(get_session)],
) -> DAGCollectionResponse:
"""Get all DAGs."""
- allowed_sorting_attrs = ["dag_id"]
dags_query = select(DagModel)
- if only_active:
- dags_query = dags_query.where(DagModel.is_active)
- if paused is not None:
- if paused:
- dags_query = dags_query.where(DagModel.is_paused)
- else:
- dags_query = dags_query.where(~DagModel.is_paused)
- if dag_id_pattern:
- dags_query = dags_query.where(DagModel.dag_id.ilike(f"%{dag_id_pattern}%"))
+
+ dags_query = apply_filters_to_query(dags_query, [only_active, paused, dag_id_pattern, tags])
# TODO: Re-enable when permissions are handled.
# readable_dags = get_auth_manager().get_permitted_dag_ids(user=g.user)
# dags_query = dags_query.where(DagModel.dag_id.in_(readable_dags))
- if tags:
- cond = [DagModel.tags.any(DagTag.name == tag) for tag in tags]
- dags_query = dags_query.where(or_(*cond))
-
total_entries = get_query_count(dags_query, session=session)
- dags_query = apply_sorting(dags_query, order_by, {}, allowed_sorting_attrs)
- dags = session.scalars(dags_query.offset(offset).limit(limit)).all()
+
+ dags_query = apply_filters_to_query(dags_query, [order_by, offset, limit])
+
+ dags = session.scalars(dags_query).all()
Review Comment:
Do you happen do have found a good documentation on SQLAlchemy internal types and how to type annotate sqlalchemy expressions (columns, selectables, filters, cte, etc...) I can't put my hand on that in their doc. I remember having the same issue with 1.x version.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1768665953
##########
airflow/api_fastapi/views/public/dags.py:
##########
@@ -35,39 +42,29 @@
@dags_router.get("/dags")
async def get_dags(
*,
- limit: int = 100,
- offset: int = 0,
- tags: Annotated[list[str] | None, Query()] = None,
- dag_id_pattern: str | None = None,
- only_active: bool = True,
- paused: bool | None = None,
- order_by: str = "dag_id",
+ limit: QueryLimit,
+ offset: QueryOffset,
+ tags: QueryTagsFilter,
+ dag_id_pattern: QueryDagIdPatternSearch,
+ only_active: QueryOnlyActiveFilter,
+ paused: QueryPausedFilter,
+ order_by: Annotated[SortParam, Depends(SortParam(["dag_id"]))],
session: Annotated[Session, Depends(get_session)],
) -> DAGCollectionResponse:
"""Get all DAGs."""
- allowed_sorting_attrs = ["dag_id"]
dags_query = select(DagModel)
- if only_active:
- dags_query = dags_query.where(DagModel.is_active)
- if paused is not None:
- if paused:
- dags_query = dags_query.where(DagModel.is_paused)
- else:
- dags_query = dags_query.where(~DagModel.is_paused)
- if dag_id_pattern:
- dags_query = dags_query.where(DagModel.dag_id.ilike(f"%{dag_id_pattern}%"))
+
+ dags_query = apply_filters_to_query(dags_query, [only_active, paused, dag_id_pattern, tags])
# TODO: Re-enable when permissions are handled.
# readable_dags = get_auth_manager().get_permitted_dag_ids(user=g.user)
# dags_query = dags_query.where(DagModel.dag_id.in_(readable_dags))
- if tags:
- cond = [DagModel.tags.any(DagTag.name == tag) for tag in tags]
- dags_query = dags_query.where(or_(*cond))
-
total_entries = get_query_count(dags_query, session=session)
- dags_query = apply_sorting(dags_query, order_by, {}, allowed_sorting_attrs)
- dags = session.scalars(dags_query.offset(offset).limit(limit)).all()
+
+ dags_query = apply_filters_to_query(dags_query, [order_by, offset, limit])
+
+ dags = session.scalars(dags_query).all()
Review Comment:
I'm not super familiar with all the changes introduced in sqlalchemy 2.0. Thanks for the advice i'll update that.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1768665953
##########
airflow/api_fastapi/views/public/dags.py:
##########
@@ -35,39 +42,29 @@
@dags_router.get("/dags")
async def get_dags(
*,
- limit: int = 100,
- offset: int = 0,
- tags: Annotated[list[str] | None, Query()] = None,
- dag_id_pattern: str | None = None,
- only_active: bool = True,
- paused: bool | None = None,
- order_by: str = "dag_id",
+ limit: QueryLimit,
+ offset: QueryOffset,
+ tags: QueryTagsFilter,
+ dag_id_pattern: QueryDagIdPatternSearch,
+ only_active: QueryOnlyActiveFilter,
+ paused: QueryPausedFilter,
+ order_by: Annotated[SortParam, Depends(SortParam(["dag_id"]))],
session: Annotated[Session, Depends(get_session)],
) -> DAGCollectionResponse:
"""Get all DAGs."""
- allowed_sorting_attrs = ["dag_id"]
dags_query = select(DagModel)
- if only_active:
- dags_query = dags_query.where(DagModel.is_active)
- if paused is not None:
- if paused:
- dags_query = dags_query.where(DagModel.is_paused)
- else:
- dags_query = dags_query.where(~DagModel.is_paused)
- if dag_id_pattern:
- dags_query = dags_query.where(DagModel.dag_id.ilike(f"%{dag_id_pattern}%"))
+
+ dags_query = apply_filters_to_query(dags_query, [only_active, paused, dag_id_pattern, tags])
# TODO: Re-enable when permissions are handled.
# readable_dags = get_auth_manager().get_permitted_dag_ids(user=g.user)
# dags_query = dags_query.where(DagModel.dag_id.in_(readable_dags))
- if tags:
- cond = [DagModel.tags.any(DagTag.name == tag) for tag in tags]
- dags_query = dags_query.where(or_(*cond))
-
total_entries = get_query_count(dags_query, session=session)
- dags_query = apply_sorting(dags_query, order_by, {}, allowed_sorting_attrs)
- dags = session.scalars(dags_query.offset(offset).limit(limit)).all()
+
+ dags_query = apply_filters_to_query(dags_query, [order_by, offset, limit])
+
+ dags = session.scalars(dags_query).all()
Review Comment:
I'm not super familiar with all the changes introduced in sqlalchemy 2.0 I would have to read the doc here.
Thanks for the advice i'll update that.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "jedcunningham (via GitHub)" <gi...@apache.org>.
jedcunningham commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1768959271
##########
airflow/api_fastapi/db.py:
##########
@@ -19,6 +19,9 @@
from typing import TYPE_CHECKING
+from sqlalchemy.sql import Select
+
+from airflow.api_fastapi.parameters import BaseParam
Review Comment:
Should move these into the `if TYPE_CHECKING` block below, no?
##########
airflow/api_fastapi/parameters.py:
##########
@@ -0,0 +1,165 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import Any, Generic, List, TypeVar, Union
+
+from fastapi import Depends, HTTPException, Query as Query
Review Comment:
```suggestion
from fastapi import Depends, HTTPException, Query
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1771035144
##########
airflow/api_fastapi/parameters.py:
##########
@@ -0,0 +1,165 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import Any, Generic, List, TypeVar, Union
+
+from fastapi import Depends, HTTPException, Query as Query
+from sqlalchemy import or_
+from sqlalchemy.sql import ColumnElement, Select
+from typing_extensions import Annotated, Self
+
+from airflow.models.dag import DagModel, DagTag
+
+T = TypeVar("T")
+
+
+class BaseParam(Generic[T], ABC):
+ """Base class for filters."""
+
+ def __init__(self) -> None:
+ self.value: T | None = None
+ self.attribute: ColumnElement | None = None
+
+ @abstractmethod
+ def to_orm(self, select: Select) -> Select:
+ pass
+
+ @abstractmethod
+ def __call__(self, *args: Any, **kwarg: Any) -> BaseParam:
+ pass
+
+ def set_value(self, value: T) -> Self:
+ self.value = value
+ return self
+
+
+class _LimitFilter(BaseParam[int]):
+ """Filter on the limit."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+
+ return select.limit(self.value)
+
+ def __call__(self, limit: int = 100) -> _LimitFilter:
+ self.value = limit
+
+ return self
+
+
+class _OffsetFilter(BaseParam[int]):
+ """Filter on offset."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.offset(self.value)
+
+ def __call__(self, offset: int = 0) -> _OffsetFilter:
+ self.value = offset
+
+ return self
+
+
+class _PausedFilter(BaseParam[Union[bool, None]]):
+ """Filter on is_paused."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.where(DagModel.is_paused == self.value)
+
+ def __call__(self, paused: bool | None = Query(default=None)) -> _PausedFilter:
+ return self.set_value(paused)
+
+
+class _OnlyActiveFilter(BaseParam[bool]):
+ """Filter on is_active."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value:
+ return select.where(DagModel.is_active == self.value)
+ return select
+
+ def __call__(self, only_active: bool = Query(default=True)) -> _OnlyActiveFilter:
+ return self.set_value(only_active)
+
+
+class _DagIdPatternSearch(BaseParam[Union[str, None]]):
+ """Search on dag_id."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.where(DagModel.dag_id.ilike(f"%{self.value}"))
+
+ def __call__(self, dag_id_pattern: str | None = Query(default=None)) -> _DagIdPatternSearch:
+ return self.set_value(dag_id_pattern)
+
+
+class SortParam(BaseParam[Union[str]]):
+ """Order result by the attribute."""
+
+ def __init__(self, allowed_attrs: list[str]) -> None:
+ super().__init__()
+ self.allowed_attrs = allowed_attrs
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+
+ lstriped_orderby = self.value.lstrip("-")
+ if self.allowed_attrs and lstriped_orderby not in self.allowed_attrs:
+ raise HTTPException(
+ 400,
+ f"Ordering with '{lstriped_orderby}' is disallowed or "
+ f"the attribute does not exist on the model",
+ )
+ if self.value[0] == "-":
+ return select.order_by(getattr(DagModel, lstriped_orderby).desc())
+ else:
+ return select.order_by(getattr(DagModel, lstriped_orderby).asc())
+ return select
+
+ def __call__(self, order_by: str = Query(default="dag_id")) -> SortParam:
+ return self.set_value(order_by)
+
+
+class _TagsFilter(BaseParam[List[str]]):
+ """Filter on tags."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value:
+ conditions = [DagModel.tags.any(DagTag.name == tag) for tag in self.value]
+ return select.where(or_(*conditions))
+
+ return select
Review Comment:
👍 thanks, done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1771044049
##########
airflow/api_fastapi/parameters.py:
##########
@@ -0,0 +1,165 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import Any, Generic, List, TypeVar, Union
+
+from fastapi import Depends, HTTPException, Query as Query
Review Comment:
Thanks, refactoring remnant. removed
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1768280280
##########
airflow/api_fastapi/parameters.py:
##########
@@ -0,0 +1,166 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import Any, Generic, List, TypeVar, Union
+
+from fastapi import Depends, HTTPException, Query as FastAPIQuery
+from sqlalchemy import or_
+from sqlalchemy.orm import Query
+from sqlalchemy.sql import ColumnElement
+from typing_extensions import Annotated, Self
+
+from airflow.models.dag import DagModel, DagTag
+
+T = TypeVar("T")
+
+
+class BaseParam(Generic[T], ABC):
+ """Base class for filters."""
+
+ def __init__(self) -> None:
+ self.value: T | None = None
+ self.attribute: ColumnElement | None = None
+
+ @abstractmethod
+ def to_orm(self, query: Query) -> Query:
+ pass
+
+ @abstractmethod
+ def __call__(self, *args: Any, **kwarg: Any) -> BaseParam:
+ pass
+
+ def set_value(self, value: T) -> Self:
+ self.value = value
+ return self
+
+
+class _LimitFilter(BaseParam[int]):
+ """Filter on the limit."""
+
+ def to_orm(self, query: Query) -> Query:
+ if self.value is None:
+ return query
+
+ return query.limit(self.value)
+
+ def __call__(self, limit: int = 100) -> _LimitFilter:
+ self.value = limit
+
+ return self
+
+
+class _OffsetFilter(BaseParam[int]):
+ """Filter on offset."""
+
+ def to_orm(self, query: Query) -> Query:
+ if self.value is None:
+ return query
+ return query.offset(self.value)
+
+ def __call__(self, offset: int = 0) -> _OffsetFilter:
+ self.value = offset
+
+ return self
+
+
+class _PausedFilter(BaseParam[Union[bool, None]]):
+ """Filter on is_paused."""
+
+ def to_orm(self, query: Query) -> Query:
+ if self.value is None:
+ return query
+ return query.where(DagModel.is_paused == self.value)
+
+ def __call__(self, paused: bool | None = FastAPIQuery(default=None)) -> _PausedFilter:
+ return self.set_value(paused)
+
+
+class _OnlyActiveFilter(BaseParam[bool]):
+ """Filter on is_active."""
+
+ def to_orm(self, query: Query) -> Query:
Review Comment:
Thanks, updated.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1769185762
##########
airflow/api_fastapi/parameters.py:
##########
@@ -0,0 +1,165 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import Any, Generic, List, TypeVar, Union
+
+from fastapi import Depends, HTTPException, Query as Query
+from sqlalchemy import or_
+from sqlalchemy.sql import ColumnElement, Select
+from typing_extensions import Annotated, Self
+
+from airflow.models.dag import DagModel, DagTag
+
+T = TypeVar("T")
+
+
+class BaseParam(Generic[T], ABC):
+ """Base class for filters."""
+
+ def __init__(self) -> None:
+ self.value: T | None = None
+ self.attribute: ColumnElement | None = None
+
+ @abstractmethod
+ def to_orm(self, select: Select) -> Select:
+ pass
+
+ @abstractmethod
+ def __call__(self, *args: Any, **kwarg: Any) -> BaseParam:
+ pass
+
+ def set_value(self, value: T) -> Self:
+ self.value = value
+ return self
+
+
+class _LimitFilter(BaseParam[int]):
+ """Filter on the limit."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+
+ return select.limit(self.value)
+
+ def __call__(self, limit: int = 100) -> _LimitFilter:
+ self.value = limit
+
+ return self
+
+
+class _OffsetFilter(BaseParam[int]):
+ """Filter on offset."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.offset(self.value)
+
+ def __call__(self, offset: int = 0) -> _OffsetFilter:
+ self.value = offset
+
+ return self
+
+
+class _PausedFilter(BaseParam[Union[bool, None]]):
+ """Filter on is_paused."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.where(DagModel.is_paused == self.value)
+
+ def __call__(self, paused: bool | None = Query(default=None)) -> _PausedFilter:
+ return self.set_value(paused)
+
+
+class _OnlyActiveFilter(BaseParam[bool]):
+ """Filter on is_active."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value:
+ return select.where(DagModel.is_active == self.value)
+ return select
+
+ def __call__(self, only_active: bool = Query(default=True)) -> _OnlyActiveFilter:
+ return self.set_value(only_active)
+
+
+class _DagIdPatternSearch(BaseParam[Union[str, None]]):
+ """Search on dag_id."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.where(DagModel.dag_id.ilike(f"%{self.value}"))
+
+ def __call__(self, dag_id_pattern: str | None = Query(default=None)) -> _DagIdPatternSearch:
+ return self.set_value(dag_id_pattern)
+
+
+class SortParam(BaseParam[Union[str]]):
+ """Order result by the attribute."""
+
+ def __init__(self, allowed_attrs: list[str]) -> None:
+ super().__init__()
+ self.allowed_attrs = allowed_attrs
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+
+ lstriped_orderby = self.value.lstrip("-")
+ if self.allowed_attrs and lstriped_orderby not in self.allowed_attrs:
+ raise HTTPException(
+ 400,
+ f"Ordering with '{lstriped_orderby}' is disallowed or "
+ f"the attribute does not exist on the model",
+ )
+ if self.value[0] == "-":
+ return select.order_by(getattr(DagModel, lstriped_orderby).desc())
+ else:
+ return select.order_by(getattr(DagModel, lstriped_orderby).asc())
+ return select
Review Comment:
+1 but then it needs to be:
```suggestion
return select.order_by(getattr(DagModel, lstriped_orderby).asc())
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1769180731
##########
airflow/api_fastapi/openapi/v1-generated.yaml:
##########
@@ -60,11 +60,9 @@ paths:
in: query
required: false
schema:
- anyOf:
- - type: array
- items:
- type: string
- - type: 'null'
+ type: array
Review Comment:
Does this chane not create the requirement to always pass at least an empty array and does not allow skipping this filter? Is this a breaking change or do I mis-interpret?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "ephraimbuddy (via GitHub)" <gi...@apache.org>.
ephraimbuddy commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1765386933
##########
airflow/api_fastapi/parameters.py:
##########
@@ -0,0 +1,166 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import Any, Generic, List, TypeVar, Union
+
+from fastapi import Depends, HTTPException, Query as FastAPIQuery
+from sqlalchemy import or_
+from sqlalchemy.orm import Query
+from sqlalchemy.sql import ColumnElement
+from typing_extensions import Annotated, Self
+
+from airflow.models.dag import DagModel, DagTag
+
+T = TypeVar("T")
+
+
+class BaseParam(Generic[T], ABC):
+ """Base class for filters."""
+
+ def __init__(self) -> None:
+ self.value: T | None = None
+ self.attribute: ColumnElement | None = None
+
+ @abstractmethod
+ def to_orm(self, query: Query) -> Query:
+ pass
+
+ @abstractmethod
+ def __call__(self, *args: Any, **kwarg: Any) -> BaseParam:
+ pass
+
+ def set_value(self, value: T) -> Self:
+ self.value = value
+ return self
+
+
+class _LimitFilter(BaseParam[int]):
+ """Filter on the limit."""
+
+ def to_orm(self, query: Query) -> Query:
+ if self.value is None:
+ return query
+
+ return query.limit(self.value)
+
+ def __call__(self, limit: int = 100) -> _LimitFilter:
+ self.value = limit
+
+ return self
+
+
+class _OffsetFilter(BaseParam[int]):
+ """Filter on offset."""
+
+ def to_orm(self, query: Query) -> Query:
+ if self.value is None:
+ return query
+ return query.offset(self.value)
+
+ def __call__(self, offset: int = 0) -> _OffsetFilter:
+ self.value = offset
+
+ return self
+
+
+class _PausedFilter(BaseParam[Union[bool, None]]):
+ """Filter on is_paused."""
+
+ def to_orm(self, query: Query) -> Query:
+ if self.value is None:
+ return query
+ return query.where(DagModel.is_paused == self.value)
+
+ def __call__(self, paused: bool | None = FastAPIQuery(default=None)) -> _PausedFilter:
+ return self.set_value(paused)
+
+
+class _OnlyActiveFilter(BaseParam[bool]):
+ """Filter on is_active."""
+
+ def to_orm(self, query: Query) -> Query:
Review Comment:
```suggestion
def to_orm(self, query: Select) -> Query:
```
I think it's a Select object and not a query.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1769177582
##########
airflow/api_fastapi/db.py:
##########
@@ -19,6 +19,9 @@
from typing import TYPE_CHECKING
+from sqlalchemy.sql import Select
+
+from airflow.api_fastapi.parameters import BaseParam
Review Comment:
Would not `ruff` tell you so :-D
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1771049009
##########
airflow/api_fastapi/parameters.py:
##########
@@ -0,0 +1,165 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import Any, Generic, List, TypeVar, Union
+
+from fastapi import Depends, HTTPException, Query as Query
+from sqlalchemy import or_
+from sqlalchemy.sql import ColumnElement, Select
+from typing_extensions import Annotated, Self
+
+from airflow.models.dag import DagModel, DagTag
+
+T = TypeVar("T")
+
+
+class BaseParam(Generic[T], ABC):
+ """Base class for filters."""
+
+ def __init__(self) -> None:
+ self.value: T | None = None
+ self.attribute: ColumnElement | None = None
+
+ @abstractmethod
+ def to_orm(self, select: Select) -> Select:
+ pass
+
+ @abstractmethod
+ def __call__(self, *args: Any, **kwarg: Any) -> BaseParam:
+ pass
+
+ def set_value(self, value: T) -> Self:
+ self.value = value
+ return self
+
+
+class _LimitFilter(BaseParam[int]):
+ """Filter on the limit."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+
+ return select.limit(self.value)
+
+ def __call__(self, limit: int = 100) -> _LimitFilter:
+ self.value = limit
+
+ return self
+
+
+class _OffsetFilter(BaseParam[int]):
+ """Filter on offset."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.offset(self.value)
+
+ def __call__(self, offset: int = 0) -> _OffsetFilter:
+ self.value = offset
+
+ return self
+
+
+class _PausedFilter(BaseParam[Union[bool, None]]):
+ """Filter on is_paused."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.where(DagModel.is_paused == self.value)
+
+ def __call__(self, paused: bool | None = Query(default=None)) -> _PausedFilter:
+ return self.set_value(paused)
+
+
+class _OnlyActiveFilter(BaseParam[bool]):
+ """Filter on is_active."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value:
+ return select.where(DagModel.is_active == self.value)
+ return select
+
+ def __call__(self, only_active: bool = Query(default=True)) -> _OnlyActiveFilter:
+ return self.set_value(only_active)
+
+
+class _DagIdPatternSearch(BaseParam[Union[str, None]]):
+ """Search on dag_id."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.where(DagModel.dag_id.ilike(f"%{self.value}"))
+
+ def __call__(self, dag_id_pattern: str | None = Query(default=None)) -> _DagIdPatternSearch:
+ return self.set_value(dag_id_pattern)
+
+
+class SortParam(BaseParam[Union[str]]):
+ """Order result by the attribute."""
+
+ def __init__(self, allowed_attrs: list[str]) -> None:
+ super().__init__()
+ self.allowed_attrs = allowed_attrs
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+
+ lstriped_orderby = self.value.lstrip("-")
+ if self.allowed_attrs and lstriped_orderby not in self.allowed_attrs:
+ raise HTTPException(
+ 400,
+ f"Ordering with '{lstriped_orderby}' is disallowed or "
+ f"the attribute does not exist on the model",
+ )
+ if self.value[0] == "-":
+ return select.order_by(getattr(DagModel, lstriped_orderby).desc())
+ else:
+ return select.order_by(getattr(DagModel, lstriped_orderby).asc())
+ return select
Review Comment:
Thanks, updated.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1771033848
##########
airflow/api_fastapi/parameters.py:
##########
@@ -0,0 +1,165 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import Any, Generic, List, TypeVar, Union
+
+from fastapi import Depends, HTTPException, Query as Query
+from sqlalchemy import or_
+from sqlalchemy.sql import ColumnElement, Select
+from typing_extensions import Annotated, Self
+
+from airflow.models.dag import DagModel, DagTag
+
+T = TypeVar("T")
+
+
+class BaseParam(Generic[T], ABC):
+ """Base class for filters."""
+
+ def __init__(self) -> None:
+ self.value: T | None = None
+ self.attribute: ColumnElement | None = None
+
+ @abstractmethod
+ def to_orm(self, select: Select) -> Select:
+ pass
+
+ @abstractmethod
+ def __call__(self, *args: Any, **kwarg: Any) -> BaseParam:
+ pass
+
+ def set_value(self, value: T) -> Self:
+ self.value = value
+ return self
+
+
+class _LimitFilter(BaseParam[int]):
+ """Filter on the limit."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+
+ return select.limit(self.value)
+
+ def __call__(self, limit: int = 100) -> _LimitFilter:
+ self.value = limit
+
+ return self
+
+
+class _OffsetFilter(BaseParam[int]):
+ """Filter on offset."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.offset(self.value)
+
+ def __call__(self, offset: int = 0) -> _OffsetFilter:
+ self.value = offset
+
+ return self
+
+
+class _PausedFilter(BaseParam[Union[bool, None]]):
+ """Filter on is_paused."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.where(DagModel.is_paused == self.value)
+
+ def __call__(self, paused: bool | None = Query(default=None)) -> _PausedFilter:
+ return self.set_value(paused)
+
+
+class _OnlyActiveFilter(BaseParam[bool]):
+ """Filter on is_active."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value:
+ return select.where(DagModel.is_active == self.value)
+ return select
+
+ def __call__(self, only_active: bool = Query(default=True)) -> _OnlyActiveFilter:
+ return self.set_value(only_active)
+
+
+class _DagIdPatternSearch(BaseParam[Union[str, None]]):
+ """Search on dag_id."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+ return select.where(DagModel.dag_id.ilike(f"%{self.value}"))
+
+ def __call__(self, dag_id_pattern: str | None = Query(default=None)) -> _DagIdPatternSearch:
+ return self.set_value(dag_id_pattern)
+
+
+class SortParam(BaseParam[Union[str]]):
+ """Order result by the attribute."""
+
+ def __init__(self, allowed_attrs: list[str]) -> None:
+ super().__init__()
+ self.allowed_attrs = allowed_attrs
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+
+ lstriped_orderby = self.value.lstrip("-")
+ if self.allowed_attrs and lstriped_orderby not in self.allowed_attrs:
+ raise HTTPException(
+ 400,
+ f"Ordering with '{lstriped_orderby}' is disallowed or "
+ f"the attribute does not exist on the model",
+ )
+ if self.value[0] == "-":
+ return select.order_by(getattr(DagModel, lstriped_orderby).desc())
+ else:
+ return select.order_by(getattr(DagModel, lstriped_orderby).asc())
+ return select
Review Comment:
Thanks, indeed.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "jedcunningham (via GitHub)" <gi...@apache.org>.
jedcunningham commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1768956574
##########
airflow/api_fastapi/parameters.py:
##########
@@ -0,0 +1,165 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import Any, Generic, List, TypeVar, Union
+
+from fastapi import Depends, HTTPException, Query as Query
+from sqlalchemy import or_
+from sqlalchemy.sql import ColumnElement, Select
+from typing_extensions import Annotated, Self
+
+from airflow.models.dag import DagModel, DagTag
+
+T = TypeVar("T")
+
+
+class BaseParam(Generic[T], ABC):
+ """Base class for filters."""
+
+ def __init__(self) -> None:
+ self.value: T | None = None
+ self.attribute: ColumnElement | None = None
+
+ @abstractmethod
+ def to_orm(self, select: Select) -> Select:
+ pass
+
+ @abstractmethod
+ def __call__(self, *args: Any, **kwarg: Any) -> BaseParam:
+ pass
+
+ def set_value(self, value: T) -> Self:
+ self.value = value
+ return self
+
+
+class _LimitFilter(BaseParam[int]):
+ """Filter on the limit."""
+
+ def to_orm(self, select: Select) -> Select:
+ if self.value is None:
+ return select
+
+ return select.limit(self.value)
+
+ def __call__(self, limit: int = 100) -> _LimitFilter:
+ self.value = limit
+
+ return self
Review Comment:
```suggestion
return self.set_value(limit)
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1768677888
##########
airflow/api_fastapi/views/public/dags.py:
##########
@@ -35,39 +42,29 @@
@dags_router.get("/dags")
async def get_dags(
*,
- limit: int = 100,
- offset: int = 0,
- tags: Annotated[list[str] | None, Query()] = None,
- dag_id_pattern: str | None = None,
- only_active: bool = True,
- paused: bool | None = None,
- order_by: str = "dag_id",
+ limit: QueryLimit,
+ offset: QueryOffset,
+ tags: QueryTagsFilter,
+ dag_id_pattern: QueryDagIdPatternSearch,
+ only_active: QueryOnlyActiveFilter,
+ paused: QueryPausedFilter,
+ order_by: Annotated[SortParam, Depends(SortParam(["dag_id"]))],
session: Annotated[Session, Depends(get_session)],
) -> DAGCollectionResponse:
"""Get all DAGs."""
- allowed_sorting_attrs = ["dag_id"]
dags_query = select(DagModel)
- if only_active:
- dags_query = dags_query.where(DagModel.is_active)
- if paused is not None:
- if paused:
- dags_query = dags_query.where(DagModel.is_paused)
- else:
- dags_query = dags_query.where(~DagModel.is_paused)
- if dag_id_pattern:
- dags_query = dags_query.where(DagModel.dag_id.ilike(f"%{dag_id_pattern}%"))
+
+ dags_query = apply_filters_to_query(dags_query, [only_active, paused, dag_id_pattern, tags])
# TODO: Re-enable when permissions are handled.
# readable_dags = get_auth_manager().get_permitted_dag_ids(user=g.user)
# dags_query = dags_query.where(DagModel.dag_id.in_(readable_dags))
- if tags:
- cond = [DagModel.tags.any(DagTag.name == tag) for tag in tags]
- dags_query = dags_query.where(or_(*cond))
-
total_entries = get_query_count(dags_query, session=session)
- dags_query = apply_sorting(dags_query, order_by, {}, allowed_sorting_attrs)
- dags = session.scalars(dags_query.offset(offset).limit(limit)).all()
+
+ dags_query = apply_filters_to_query(dags_query, [order_by, offset, limit])
+
+ dags = session.scalars(dags_query).all()
Review Comment:
Done, that's even better because I do not have a name conflict between `sqlalchemy.sql.Query` and `fastapi.Query`, I don't have to alias anymore.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1771045920
##########
airflow/api_fastapi/openapi/v1-generated.yaml:
##########
@@ -60,11 +60,9 @@ paths:
in: query
required: false
schema:
- anyOf:
- - type: array
- items:
- type: string
- - type: 'null'
+ type: array
Review Comment:
'required: false', an empty list is provided if the query param is missing. We can still omit it and no filtering will happen.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1771066684
##########
airflow/api_fastapi/db.py:
##########
@@ -19,6 +19,9 @@
from typing import TYPE_CHECKING
+from sqlalchemy.sql import Select
+
+from airflow.api_fastapi.parameters import BaseParam
Review Comment:
"TCH001" and "TCH002" are disabled on `api_fastapi` folder. Same reason as for `serialization/pydantic/` pydantic manipulates annotations at runtime and this things will fail.
Also fails to detect `Annotated[type, ...]` depends as required at runtime. Moving things to such codeblock will fail. I don't think theres really a better workaround considering our constraints:
- We need `from future import __annotation__` in the file.
- We want to support python 3.8 and 3.9
I moved to type checking block those that are not throwing errors.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #42320:
URL: https://github.com/apache/airflow/pull/42320#discussion_r1771066684
##########
airflow/api_fastapi/db.py:
##########
@@ -19,6 +19,9 @@
from typing import TYPE_CHECKING
+from sqlalchemy.sql import Select
+
+from airflow.api_fastapi.parameters import BaseParam
Review Comment:
"TCH001" and "TCH002" are disabled on `api_fastapi` folder. Same reason as for `serialization/pydantic/` pydantic manipulates annotations at runtime and this things will fail.
Also `Annotated` for old python version and future __annotations__ are not working well.
I moved to type checking block those that are not throwing errors.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] FastAPI API Add test query params standardization an reusability [airflow]
Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun merged PR #42320:
URL: https://github.com/apache/airflow/pull/42320
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org