简体   繁体   English

如何从 Python 中的另一个文件为 PythonOperator 调用 function

[英]How to call a function from another file in Python for PythonOperator

I'm writing a Airflow DAG that uses a PythonOperator.我正在编写一个使用 PythonOperator 的 Airflow DAG。 It requires a "python_callable" which it seems to be a function. I'm calling this Python code dag-transf.py它需要一个“python_callable”,它似乎是一个 function。我称这个 Python 代码为dag-transf.py

I have a Python code that does some transformation through pandas (transf.py)我有一个 Python 代码,它通过 pandas (transf.py)做一些转换

I need dag-transf.py task to execute transf-py as the "python_callable" parameter.我需要 dag-transf.py 任务来执行 transf-py 作为“python_callable”参数。

with DAG(dag_id='dag_transformation',
         default_args=default_args,
         catchup=False,
         schedule_interval="0 0 1 * *") as dag:

    exporting = PythonOperator(
        task_id='exporting_task',
        python_callable=transf_function #transf_function needs to actually be transf.py

How am I supposed to use this external file as the function code itself?我应该如何将这个外部文件用作 function 代码本身?

You can read the https://airflow.apache.org/docs/apache-airflow/stable/modules_management.html docs.您可以阅读https://airflow.apache.org/docs/apache-airflow/stable/modules_management.html文档。

You really need to define a package/module where your function can be imported from.你真的需要定义一个包/模块,你的 function 可以从中导入。 This is standard Python way of importing and using functions.这是导入和使用函数的标准 Python 方式。 The only 'airflow` related thing is where you should create packages and modules - they all should be creaed in the "dags folder where you can import them from (but ready the doc above to get details of it.唯一与“airflow”相关的是你应该在哪里创建包和模块——它们都应该在“dags”文件夹中创建,你可以从中导入它们(但准备好上面的文档以获取它的详细信息。

Create a python file in the DAG Directory.在 DAG 目录中创建一个 python 文件。

  • dag_trans.py dag_trans.py

Write your transf_function inside the created file.在创建的文件中写入您的transf_function

In your dag, import your python package在你的 dag 中,导入你的 python package

from dag_trans import transf_function

Then use:然后使用:

python_callable=transf_function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM