Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing local module (python script) in Airflow DAG

Tags:

python

airflow

I'm trying to import a local module (a python script) to my DAG.

Directory structure:

airflow/ ├── dag │   ├── __init__.py │   └── my_DAG.py └── script     └── subfolder         ├── __init__.py         └── local_module.py  

Sample code in my_DAG.py:

#trying to import from local module from script.subfolder import local_module    #calling a function in local_module.py   a = some_function()   

I get an error in Airflow saying 'Broken DAG: my_DAG. No module named 'local_module'.

I've updated Airflow to 1.9.0 but this doesn't fix the issue.

  • What is the solution here?
  • I also read somewhere that I could solve this by creating a plugin. Can anyone point to how I can do this?

Thanks.

like image 243
badangatal Avatar asked May 03 '18 08:05

badangatal


People also ask

How do I install Python modules in Airflow?

You can do it in one of those ways: add your modules to one of the folders that Airflow automatically adds to PYTHONPATH. add extra folders where you keep your code to PYTHONPATH. package your code into a Python package and install it together with Airflow.

What is __ init __ PY for?

The __init__.py file makes Python treat directories containing it as modules. Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.


1 Answers

This usually has to do with how Airflow is configured.

In airflow.cfg, make sure the path in airflow_home is correctly set to the path the Airflow directory strucure is in.

Then Airflow scans all subfolders and populates them so that modules can be found.

Otherwise, just make sure the folder you are trying to import is in the Python path: How to use PYTHONPATH

like image 135
tobi6 Avatar answered Oct 23 '22 18:10

tobi6