ashb commented on a change in pull request #15425:
URL: https://github.com/apache/airflow/pull/15425#discussion_r629299429
##########
File path: airflow/models/connection.py
##########
@@ -377,3 +378,50 @@ def get_connection_from_secrets(cls, conn_id: str) ->
'Connection':
if conn:
return conn
raise AirflowNotFoundException(f"The conn_id `{conn_id}` isn't
defined")
+
+ @classmethod
+ def get_connection_parameter_names(cls) -> Set[str]:
+ """Returns :class:`airflow.models.connection.Connection` constructor
parameters."""
+ return {k for k in signature(cls.__init__).parameters.keys() if k !=
"self"}
+
+ @classmethod
+ def from_dict(cls, conn_id: str, conn_dict: Dict) -> 'Connection':
+ """
+ Create a connection from a dictionary.
+
+ :param conn_dict: dictionary representing a connection's attributes
+ e.g., {'conn_id': '', 'conn_type': '', 'login': '', ...}
+ :return: connection
+ """
+ if not isinstance(conn_dict, dict):
+ raise AirflowException(
+ f"Unexpected conn_dict type: {type(conn_dict)}. "
+ "The connection must be defined as a dictionary."
+ )
+
+ connection_parameter_names = cls.get_connection_parameter_names() |
{"extra_dejson"}
+ current_keys = set(conn_dict.keys())
+ if not current_keys.issubset(connection_parameter_names):
+ illegal_keys = current_keys - connection_parameter_names
+ illegal_keys_list = ", ".join(sorted(illegal_keys))
+ raise AirflowException(
+ f"The object have illegal keys: {illegal_keys_list}. "
Review comment:
```suggestion
f"The connection dict has illegal keys: {illegal_keys_list}.
"
```
##########
File path: airflow/models/connection.py
##########
@@ -377,3 +378,50 @@ def get_connection_from_secrets(cls, conn_id: str) ->
'Connection':
if conn:
return conn
raise AirflowNotFoundException(f"The conn_id `{conn_id}` isn't
defined")
+
+ @classmethod
+ def get_connection_parameter_names(cls) -> Set[str]:
+ """Returns :class:`airflow.models.connection.Connection` constructor
parameters."""
+ return {k for k in signature(cls.__init__).parameters.keys() if k !=
"self"}
+
+ @classmethod
+ def from_dict(cls, conn_id: str, conn_dict: Dict) -> 'Connection':
+ """
+ Create a connection from a dictionary.
+
+ :param conn_dict: dictionary representing a connection's attributes
+ e.g., {'conn_id': '', 'conn_type': '', 'login': '', ...}
+ :return: connection
+ """
+ if not isinstance(conn_dict, dict):
+ raise AirflowException(
+ f"Unexpected conn_dict type: {type(conn_dict)}. "
+ "The connection must be defined as a dictionary."
+ )
+
+ connection_parameter_names = cls.get_connection_parameter_names() |
{"extra_dejson"}
+ current_keys = set(conn_dict.keys())
+ if not current_keys.issubset(connection_parameter_names):
+ illegal_keys = current_keys - connection_parameter_names
+ illegal_keys_list = ", ".join(sorted(illegal_keys))
+ raise AirflowException(
Review comment:
```suggestion
raise TypeError(
```
##########
File path: airflow/models/connection.py
##########
@@ -377,3 +378,50 @@ def get_connection_from_secrets(cls, conn_id: str) ->
'Connection':
if conn:
return conn
raise AirflowNotFoundException(f"The conn_id `{conn_id}` isn't
defined")
+
+ @classmethod
+ def get_connection_parameter_names(cls) -> Set[str]:
+ """Returns :class:`airflow.models.connection.Connection` constructor
parameters."""
+ return {k for k in signature(cls.__init__).parameters.keys() if k !=
"self"}
+
+ @classmethod
+ def from_dict(cls, conn_id: str, conn_dict: Dict) -> 'Connection':
+ """
+ Create a connection from a dictionary.
+
+ :param conn_dict: dictionary representing a connection's attributes
+ e.g., {'conn_id': '', 'conn_type': '', 'login': '', ...}
+ :return: connection
+ """
+ if not isinstance(conn_dict, dict):
+ raise AirflowException(
+ f"Unexpected conn_dict type: {type(conn_dict)}. "
Review comment:
```suggestion
raise TypeError(
f"Unexpected conn_dict type: {type(conn_dict).__name__}. "
```
##########
File path: airflow/utils/parse.py
##########
@@ -0,0 +1,168 @@
+#
+# 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.
+#
+
+"""Parse data from a file if it uses a valid format."""
+import json
+import logging
+import os
+from collections import defaultdict
+from json import JSONDecodeError
+from typing import Any, Dict, List, Tuple
+
+import airflow.utils.yaml as yaml
+from airflow.exceptions import AirflowException, AirflowFileParseException,
FileSyntaxError
+from airflow.utils.file import COMMENT_PATTERN
+
+log = logging.getLogger(__name__)
+
+
+def _parse_env_file(file_path: str) -> Tuple[Dict[str, List[str]],
List[FileSyntaxError]]:
+ """
+ Parse a file in the ``.env`` format.
+
+ .. code-block:: text
+
+
MY_CONN_ID=my-conn-type://my-login:my-pa%2Fssword@my-host:5432/my-schema?param1=val1¶m2=val2
+
+ :param file_path: The location of the file that will be processed.
+ :type file_path: str
+ :return: Tuple with mapping of key and list of values and list of syntax
errors
+ """
+ with open(file_path) as f:
+ content = f.read()
+
+ contents_dict: Dict[str, List[str]] = defaultdict(list)
+ errors: List[FileSyntaxError] = []
+ for line_no, line in enumerate(content.splitlines(), 1):
+ if not line:
+ # Ignore empty line
+ continue
Review comment:
> in case it had been originally committed this way intentionally
Very unlikely to have been intentional.
--
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:
[email protected]