Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.
Creación de un complemento personalizado para Apache Airflow PythonVirtualenvOperator
En el siguiente ejemplo se explica cómo parchear el Apache Airflow PythonVirtualenvOperator
con un complemento personalizado en Amazon Managed Workflows for Apache Airflow.
Temas
Version
Puede usar el ejemplo de código de esta página con Apache Airflow v2 en Python 3.10
Requisitos previos
Para usar el código de muestra de esta página, necesitará lo siguiente:
Permisos
No se necesitan permisos adicionales para usar el código de ejemplo de esta página.
Requisitos
Para usar el código de ejemplo de esta página, agregue las siguientes dependencias a su requirements.txt
. Para obtener más información, consulte. Instalación de dependencias de Python
virtualenv
Código de muestra de complemento personalizado
Apache Airflow ejecutará el contenido de los archivos de Python en la carpeta de complementos durante el arranque. Este complemento parcheará la versión integrada PythonVirtualenvOperator
durante el proceso de arranque para que sea compatible con Amazon MWAA. Los siguientes pasos muestran el código de ejemplo del complemento personalizado.
-
En la línea de comandos, navegue hasta el
plugins
directorio de la sección anterior. Por ejemplo:cd plugins
-
Copie el contenido del código de ejemplo siguiente y guárdelo localmente como
virtual_python_plugin.py
.""" Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from airflow.plugins_manager import AirflowPlugin import airflow.utils.python_virtualenv from typing import List def _generate_virtualenv_cmd(tmp_dir: str, python_bin: str, system_site_packages: bool) -> List[str]: cmd = ['python3','/usr/local/airflow/.local/lib/python3.7/site-packages/virtualenv', tmp_dir] if system_site_packages: cmd.append('--system-site-packages') if python_bin is not None: cmd.append(f'--python={python_bin}') return cmd airflow.utils.python_virtualenv._generate_virtualenv_cmd=_generate_virtualenv_cmd class VirtualPythonPlugin(AirflowPlugin): name = 'virtual_python_plugin'
Plugins.zip
En los pasos siguientes se explica cómo crear elplugins.zip
.
-
En la línea de comandos, navegue hasta el directorio
virtual_python_plugin.py
incluido en la sección anterior. Por ejemplo:cd plugins
-
Comprima el contenido de la carpeta
plugins
.zip plugins.zip virtual_python_plugin.py
Código de ejemplo
Los siguientes pasos describen cómo crear el código de DAG para el complemento personalizado.
-
En el símbolo del sistema, vaya hasta el directorio en el que esté almacenado el código DAG. Por ejemplo:
cd dags
-
Copie el contenido del código de ejemplo siguiente y guárdelo localmente como
virtualenv_test.py
.""" Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from airflow import DAG from airflow.operators.python import PythonVirtualenvOperator from airflow.utils.dates import days_ago import os os.environ["PATH"] = os.getenv("PATH") + ":/usr/local/airflow/.local/bin" def virtualenv_fn(): import boto3 print("boto3 version ",boto3.__version__) with DAG(dag_id="virtualenv_test", schedule_interval=None, catchup=False, start_date=days_ago(1)) as dag: virtualenv_task = PythonVirtualenvOperator( task_id="virtualenv_task", python_callable=virtualenv_fn, requirements=["boto3>=1.17.43"], system_site_packages=False, dag=dag, )
Opciones de configuración de Airflow
Si utiliza Apache Airflow v2, agregue core.lazy_load_plugins : False
como opción de configuración de Apache Airflow. Para obtener más información, consulte Uso de las opciones de configuración para cargar complementos en 2.
Siguientes pasos
-
Aprenda a cargar el archivo
requirements.txt
de este ejemplo a su bucket de Amazon S3 en Instalación de dependencias de Python. -
Aprenda a cargar el código el DAG de este ejemplo en la carpeta
dags
de su bucket de Amazon S3 en Añadir o actualizar DAGs. -
Obtenga más información sobre cómo cargar el archivo
plugins.zip
de este ejemplo a su bucket de Amazon S3 en Instalación de complementos personalizados.