Coverage for /pythoncovmergedfiles/medio/medio/src/airflow/build/lib/airflow/utils/json.py: 37%
65 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:35 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:35 +0000
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.
18from __future__ import annotations
20import json
21from datetime import date, datetime
22from decimal import Decimal
23from typing import Any
25from flask.json.provider import JSONProvider
27from airflow.serialization.serde import CLASSNAME, DATA, SCHEMA_ID, deserialize, serialize
28from airflow.utils.timezone import convert_to_utc, is_naive
31class AirflowJsonProvider(JSONProvider):
32 """JSON Provider for Flask app to use WebEncoder."""
34 ensure_ascii: bool = True
35 sort_keys: bool = True
37 def dumps(self, obj, **kwargs):
38 kwargs.setdefault("ensure_ascii", self.ensure_ascii)
39 kwargs.setdefault("sort_keys", self.sort_keys)
40 return json.dumps(obj, **kwargs, cls=WebEncoder)
42 def loads(self, s: str | bytes, **kwargs):
43 return json.loads(s, **kwargs)
46class WebEncoder(json.JSONEncoder):
47 """This encodes values into a web understandable format. There is no deserializer.
49 This parses datetime, dates, Decimal and bytes. In order to parse the custom
50 classes and the other types, and since it's just to show the result in the UI,
51 we return repr(object) for everything else.
52 """
54 def default(self, o: Any) -> Any:
55 if isinstance(o, datetime):
56 if is_naive(o):
57 o = convert_to_utc(o)
58 return o.isoformat()
60 if isinstance(o, date):
61 return o.strftime("%Y-%m-%d")
63 if isinstance(o, Decimal):
64 data = serialize(o)
65 if isinstance(data, dict) and DATA in data:
66 return data[DATA]
67 if isinstance(o, bytes):
68 try:
69 return o.decode("unicode_escape")
70 except UnicodeDecodeError:
71 return repr(o)
72 try:
73 data = serialize(o)
74 if isinstance(data, dict) and CLASSNAME in data:
75 # this is here for backwards compatibility
76 if (
77 data[CLASSNAME].startswith("numpy")
78 or data[CLASSNAME] == "kubernetes.client.models.v1_pod.V1Pod"
79 ):
80 return data[DATA]
81 return data
82 except TypeError:
83 return repr(o)
86class XComEncoder(json.JSONEncoder):
87 """This encoder serializes any object that has attr, dataclass or a custom serializer."""
89 def default(self, o: object) -> Any:
90 try:
91 return serialize(o)
92 except TypeError:
93 return super().default(o)
95 def encode(self, o: Any) -> str:
96 # checked here and in serialize
97 if isinstance(o, dict) and (CLASSNAME in o or SCHEMA_ID in o):
98 raise AttributeError(f"reserved key {CLASSNAME} found in dict to serialize")
100 # tuples are not preserved by std python serializer
101 if isinstance(o, tuple):
102 o = self.default(o)
104 return super().encode(o)
107class XComDecoder(json.JSONDecoder):
108 """
109 This decoder deserializes dicts to objects if they contain
110 the `__classname__` key otherwise it will return the dict
111 as is.
112 """
114 def __init__(self, *args, **kwargs) -> None:
115 if not kwargs.get("object_hook"):
116 kwargs["object_hook"] = self.object_hook
118 super().__init__(*args, **kwargs)
120 def object_hook(self, dct: dict) -> object:
121 return deserialize(dct)
123 @staticmethod
124 def orm_object_hook(dct: dict) -> object:
125 """Creates a readable representation of a serialized object."""
126 return deserialize(dct, False)
129# backwards compatibility
130AirflowJsonEncoder = WebEncoder