parameters.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. from __future__ import annotations
  18. import logging
  19. from functools import wraps
  20. from typing import TYPE_CHECKING, Any, Callable, Container, TypeVar, cast
  21. from pendulum.parsing import ParserError
  22. from sqlalchemy import text
  23. from airflow.api_connexion.exceptions import BadRequest
  24. from airflow.configuration import conf
  25. from airflow.utils import timezone
  26. if TYPE_CHECKING:
  27. from datetime import datetime
  28. from sqlalchemy.sql import Select
  29. log = logging.getLogger(__name__)
  30. def validate_istimezone(value: datetime) -> None:
  31. """Validate that a datetime is not naive."""
  32. if not value.tzinfo:
  33. raise BadRequest("Invalid datetime format", detail="Naive datetime is disallowed")
  34. def format_datetime(value: str) -> datetime:
  35. """
  36. Format datetime objects.
  37. Datetime format parser for args since connexion doesn't parse datetimes
  38. https://github.com/zalando/connexion/issues/476
  39. This should only be used within connection views because it raises 400
  40. """
  41. value = value.strip()
  42. if value[-1] != "Z":
  43. value = value.replace(" ", "+")
  44. try:
  45. return timezone.parse(value)
  46. except (ParserError, TypeError) as err:
  47. raise BadRequest("Incorrect datetime argument", detail=str(err))
  48. def check_limit(value: int) -> int:
  49. """
  50. Check the limit does not exceed configured value.
  51. This checks the limit passed to view and raises BadRequest if
  52. limit exceed user configured value
  53. """
  54. max_val = conf.getint("api", "maximum_page_limit") # user configured max page limit
  55. fallback = conf.getint("api", "fallback_page_limit")
  56. if value > max_val:
  57. log.warning(
  58. "The limit param value %s passed in API exceeds the configured maximum page limit %s",
  59. value,
  60. max_val,
  61. )
  62. return max_val
  63. if value == 0:
  64. return fallback
  65. if value < 0:
  66. raise BadRequest("Page limit must be a positive integer")
  67. return value
  68. T = TypeVar("T", bound=Callable)
  69. def format_parameters(params_formatters: dict[str, Callable[[Any], Any]]) -> Callable[[T], T]:
  70. """
  71. Create a decorator to convert parameters using given formatters.
  72. Using it allows you to separate parameter formatting from endpoint logic.
  73. :param params_formatters: Map of key name and formatter function
  74. """
  75. def format_parameters_decorator(func: T) -> T:
  76. @wraps(func)
  77. def wrapped_function(*args, **kwargs):
  78. for key, formatter in params_formatters.items():
  79. if key in kwargs:
  80. kwargs[key] = formatter(kwargs[key])
  81. return func(*args, **kwargs)
  82. return cast(T, wrapped_function)
  83. return format_parameters_decorator
  84. def apply_sorting(
  85. query: Select,
  86. order_by: str,
  87. to_replace: dict[str, str] | None = None,
  88. allowed_attrs: Container[str] | None = None,
  89. ) -> Select:
  90. """Apply sorting to query."""
  91. lstriped_orderby = order_by.lstrip("-")
  92. if allowed_attrs and lstriped_orderby not in allowed_attrs:
  93. raise BadRequest(
  94. detail=f"Ordering with '{lstriped_orderby}' is disallowed or "
  95. f"the attribute does not exist on the model"
  96. )
  97. if to_replace:
  98. lstriped_orderby = to_replace.get(lstriped_orderby, lstriped_orderby)
  99. if order_by[0] == "-":
  100. order_by = f"{lstriped_orderby} desc"
  101. else:
  102. order_by = f"{lstriped_orderby} asc"
  103. return query.order_by(text(order_by))