coufon commented on a change in pull request #5701: [AIRFLOW-5088] Add DAG 
serialization using JSON
URL: https://github.com/apache/airflow/pull/5701#discussion_r310761200
 
 

 ##########
 File path: airflow/dag/serialization.py
 ##########
 @@ -0,0 +1,316 @@
+# -*- coding: utf-8 -*-
+#
+# 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.
+
+"""DAG serialization with JSON."""
+
+from enum import Enum
+from enum import unique
+import json
+import logging
+import datetime
+import dateutil.parser
+import pendulum
+
+from airflow.models import BaseOperator
+from airflow.models import DAG
+from airflow.models.connection import Connection
+from airflow.www.utils import get_python_source
+
+
+# Serialization failure returns 'failed'.
+FAILED = 'serialization_failed'
+
+
+# Fields of an encoded object in serialization.
+@unique
+class Encoding(str, Enum):
+    """Enum of encoding constants."""
+    TYPE = '__type'
+    VAR = '__var'
+
+
+# Supported types for encoding. primitives and list are not encoded.
+@unique
+class DagTypes(str, Enum):
+    """Enum of supported attribute types of DAG."""
+    DAG = 'dag'
+    OP = 'operator'
+    DATETIME = 'datetime'
+    TIMEDELTA = 'timedelta'
+    TIMEZONE = 'timezone'
+    DICT = 'dict'
+    SET = 'set'
+    TUPLE = 'tuple'
+
+
+class Serialization():
+    """Serialization provides utils for serialization."""
+
+    # JSON primitive types.
+    _primitive_types = (int, bool, float, str)
+    # Time types.
+    _datetime_types = (datetime.datetime, datetime.date, datetime.time)
+    # Object types that are always excluded.
+    # TODO(coufon): not needed if _dag_included_fields and _op_included_fields 
are customized.
+    _excluded_types = (logging.Logger, Connection, type)
+
+    @classmethod
+    def to_json(cls, x):
+        """Stringifies DAGs and operators contained by x and returns a JSON 
string of x."""
+        return json.dumps(cls._serialize(x, {}), ensure_ascii=True)
+
+    @classmethod
+    def from_json(cls, encoded_x):
+        """Deserializes encoded_x and reconstructs all DAGs and operators it 
contains."""
+        return cls._deserialize(json.loads(encoded_x), {})
+
+    @classmethod
+    def encode(cls, x, type_):
+        """Encode data by a JSON dict."""
+        return {Encoding.VAR: x, Encoding.TYPE: type_}
+
+    @classmethod
+    def serialize_object(cls, x, visited_dags, included_fields):
+        """Helper function to serialize an object as a JSON dict."""
+        new_x = {}
+        for k in included_fields:
+            # None is ignored in serialized form and is added back in 
deserialization.
+            v = getattr(x, k, None)
+            if not cls._is_excluded(v):
+                new_x[k] = cls._serialize(v, visited_dags)
+        return new_x
+
+    @classmethod
+    def deserialize_object(cls, x, new_x, included_fields, visited_dags):
+        """Deserialize and copy the attributes of dict x to a new object new_x.
+
+        It does not create new_x because if x is a DAG, new_x should be added 
into visited_dag
+        ahead of calling this function.
+        """
+        for k in included_fields:
+            if k in x:
+                setattr(new_x, k, cls._deserialize(x[k], visited_dags))
+            else:
+                setattr(new_x, k, None)
+
+    @classmethod
+    def _is_primitive(cls, x):
+        """Primitive types."""
+        return x is None or isinstance(x, cls._primitive_types)
+
+    @classmethod
+    def _is_excluded(cls, x):
+        """Types excluded from serialization.
+
+        TODO(coufon): not needed if _dag_included_fields and 
_op_included_fields are customized.
+        """
+        return x is None or isinstance(x, cls._excluded_types)
+
+    @classmethod
+    def _serialize(cls, x, visited_dags):  # pylint: 
disable=too-many-return-statements
+        """Helper function of depth first search for serialization.
+
+        visited_dags stores DAGs that are being stringifying for have been 
stringified,
 
 Review comment:
   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.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services

Reply via email to