json.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. #
  2. # Licensed to the Apache Software Foundation (ASF) under one
  3. # or more contributor license agreements. See the NOTICE file
  4. # distributed with this work for additional information
  5. # regarding copyright ownership. The ASF licenses this file
  6. # to you under the Apache License, Version 2.0 (the
  7. # "License"); you may not use this file except in compliance
  8. # with the License. You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing,
  13. # software distributed under the License is distributed on an
  14. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. # KIND, either express or implied. See the License for the
  16. # specific language governing permissions and limitations
  17. # under the License.
  18. from __future__ import annotations
  19. import json
  20. from datetime import date, datetime
  21. from decimal import Decimal
  22. from typing import Any
  23. from flask.json.provider import JSONProvider
  24. from airflow.serialization.serde import CLASSNAME, DATA, SCHEMA_ID, deserialize, serialize
  25. from airflow.utils.timezone import convert_to_utc, is_naive
  26. class AirflowJsonProvider(JSONProvider):
  27. """JSON Provider for Flask app to use WebEncoder."""
  28. ensure_ascii: bool = True
  29. sort_keys: bool = True
  30. def dumps(self, obj, **kwargs):
  31. kwargs.setdefault("ensure_ascii", self.ensure_ascii)
  32. kwargs.setdefault("sort_keys", self.sort_keys)
  33. return json.dumps(obj, **kwargs, cls=WebEncoder)
  34. def loads(self, s: str | bytes, **kwargs):
  35. return json.loads(s, **kwargs)
  36. class WebEncoder(json.JSONEncoder):
  37. """
  38. This encodes values into a web understandable format. There is no deserializer.
  39. This parses datetime, dates, Decimal and bytes. In order to parse the custom
  40. classes and the other types, and since it's just to show the result in the UI,
  41. we return repr(object) for everything else.
  42. """
  43. def default(self, o: Any) -> Any:
  44. if isinstance(o, datetime):
  45. if is_naive(o):
  46. o = convert_to_utc(o)
  47. return o.isoformat()
  48. if isinstance(o, date):
  49. return o.strftime("%Y-%m-%d")
  50. if isinstance(o, Decimal):
  51. data = serialize(o)
  52. if isinstance(data, dict) and DATA in data:
  53. return data[DATA]
  54. if isinstance(o, bytes):
  55. try:
  56. return o.decode("unicode_escape")
  57. except UnicodeDecodeError:
  58. return repr(o)
  59. try:
  60. data = serialize(o)
  61. if isinstance(data, dict) and CLASSNAME in data:
  62. # this is here for backwards compatibility
  63. if (
  64. data[CLASSNAME].startswith("numpy")
  65. or data[CLASSNAME] == "kubernetes.client.models.v1_pod.V1Pod"
  66. ):
  67. return data[DATA]
  68. return data
  69. except TypeError:
  70. return repr(o)
  71. class XComEncoder(json.JSONEncoder):
  72. """This encoder serializes any object that has attr, dataclass or a custom serializer."""
  73. def default(self, o: object) -> Any:
  74. try:
  75. return serialize(o)
  76. except TypeError:
  77. return super().default(o)
  78. def encode(self, o: Any) -> str:
  79. # checked here and in serialize
  80. if isinstance(o, dict) and (CLASSNAME in o or SCHEMA_ID in o):
  81. raise AttributeError(f"reserved key {CLASSNAME} found in dict to serialize")
  82. # tuples are not preserved by std python serializer
  83. if isinstance(o, tuple):
  84. o = self.default(o)
  85. return super().encode(o)
  86. class XComDecoder(json.JSONDecoder):
  87. """Deserialize dicts to objects if they contain the `__classname__` key, otherwise return the dict."""
  88. def __init__(self, *args, **kwargs) -> None:
  89. if not kwargs.get("object_hook"):
  90. kwargs["object_hook"] = self.object_hook
  91. super().__init__(*args, **kwargs)
  92. def object_hook(self, dct: dict) -> object:
  93. return deserialize(dct)
  94. @staticmethod
  95. def orm_object_hook(dct: dict) -> object:
  96. """Create a readable representation of a serialized object."""
  97. return deserialize(dct, False)
  98. # backwards compatibility
  99. AirflowJsonEncoder = WebEncoder