Подтвердить что ты не робот

Воздушный поток с использованием файлов шаблонов для PythonOperator

Метод получения BashOperator или SqlOperator для получения внешнего файла для его шаблона несколько четко документирован, но, глядя на PythonOperator мой тест на то, что я понимаю из документов, не работает. Я не уверен, как параметры templates_exts и templates_dict будут правильно взаимодействовать, чтобы забрать файл.

В моей папке dags я создал: pyoptemplate.sql и pyoptemplate.t а также test_python_operator_template.py:

pyoptemplate.sql:

SELECT * FROM {{params.table}};

pyoptemplate.t:

SELECT * FROM {{params.table}};

test_python_operator_template.py:

# coding: utf-8
# vim:ai:si:et:sw=4 ts=4 tw=80
"""
# A Test of Templates in PythonOperator
"""

from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from datetime import datetime

import pprint

pp = pprint.PrettyPrinter(indent=4)


def templated_function(ds, **kwargs):
    """This function will try to use templates loaded from external files"""
    pp.pprint(ds)
    pp.pprint(kwargs)


# Define the DAG
dag = DAG(dag_id='test_python_operator_template_dag',
          default_args={"owner": "lamblin",
                        "start_date": datetime.now()},
          template_searchpath=['/Users/daniellamblin/airflow/dags'],
          schedule_interval='@once')


# Define the single task in this controller example DAG
op = PythonOperator(task_id='test_python_operator_template',
                    provide_context=True,
                    python_callable=templated_function,
                    templates_dict={
                        'pyoptemplate': '',
                        'pyoptemplate.sql': '',
                        'sql': 'pyoptemplate',
                        'file1':'pyoptemplate.sql',
                        'file2':'pyoptemplate.t',
                        'table': '{{params.table}}'},
                    templates_exts=['.sql','.t'],
                    params={'condition_param': True,
                            'message': 'Hello World',
                            'table': 'TEMP_TABLE'},
                    dag=dag)

Результат запуска показывает, что table была правильно заправлена шаблоном в виде строки, но другие не тянули файлы для шаблонов.

dlamblin$ airflow test test_python_operator_template_dag test_python_operator_template 2017-01-18
[2017-01-18 23:58:06,698] {__init__.py:36} INFO - Using executor SequentialExecutor
[2017-01-18 23:58:07,342] {models.py:154} INFO - Filling up the DagBag from /Users/daniellamblin/airflow/dags
[2017-01-18 23:58:07,620] {models.py:1196} INFO - 
--------------------------------------------------------------------------------
Starting attempt 1 of 1
--------------------------------------------------------------------------------

[2017-01-18 23:58:07,620] {models.py:1219} INFO - Executing <Task(PythonOperator): test_python_operator_template> on 2017-01-18 00:00:00
'2017-01-18'
{   u'END_DATE': '2017-01-18',
    u'conf': <module 'airflow.configuration' from '/Library/Python/2.7/site-packages/airflow/configuration.pyc'>,
    u'dag': <DAG: test_python_operator_template_dag>,
    u'dag_run': None,
    u'ds_nodash': u'20170118',
    u'end_date': '2017-01-18',
    u'execution_date': datetime.datetime(2017, 1, 18, 0, 0),
    u'latest_date': '2017-01-18',
    u'macros': <module 'airflow.macros' from '/Library/Python/2.7/site-packages/airflow/macros/__init__.pyc'>,
    u'params': {   'condition_param': True,
                   'message': 'Hello World',
                   'table': 'TEMP_TABLE'},
    u'run_id': None,
    u'tables': None,
    u'task': <Task(PythonOperator): test_python_operator_template>,
    u'task_instance': <TaskInstance: test_python_operator_template_dag.test_python_operator_template 2017-01-18 00:00:00 [running]>,
    u'task_instance_key_str': u'test_python_operator_template_dag__test_python_operator_template__20170118',
    'templates_dict': {   'file1': u'pyoptemplate.sql',
                          'file2': u'pyoptemplate.t',
                          'pyoptemplate': u'',
                          'pyoptemplate.sql': u'',
                          'sql': u'pyoptemplate',
                          'table': u'TEMP_TABLE'},
    u'test_mode': True,
    u'ti': <TaskInstance: test_python_operator_template_dag.test_python_operator_template 2017-01-18 00:00:00 [running]>,
    u'tomorrow_ds': '2017-01-19',
    u'tomorrow_ds_nodash': u'20170119',
    u'ts': '2017-01-18T00:00:00',
    u'ts_nodash': u'20170118T000000',
    u'yesterday_ds': '2017-01-17',
    u'yesterday_ds_nodash': u'20170117'}
[2017-01-18 23:58:07,634] {python_operator.py:67} INFO - Done. Returned value was: None
4b9b3361

Ответ 1

Начиная с Airflow 1.8, способ, которым PythonOperator заменяет свое поле template_ext в __init__, не работает. Задачи только проверяют template_ext на __class__. Чтобы создать PythonOperator, который собирает файлы шаблонов SQL, вам нужно только выполнить следующие действия:

class SQLTemplatedPythonOperator(PythonOperator):
    template_ext = ('.sql',)

А затем для доступа к SQL из вашей задачи при ее запуске:

SQLTemplatedPythonOperator(
    templates_dict={'query': 'my_template.sql'},
    params={'my_var': 'my_value'},
    python_callable=my_func,
    provide_context=True,
)

def my_func(**context):
    context['templates_dict']['query']

Ответ 2

Я не думаю, что это действительно возможно. Но может оказаться полезным следующее обходное решение:

def templated_function(ds, **kwargs):
    kwargs['ds'] = ds                                # put ds into 'context'
    task = kwargs['task']                            # get handle on task
    templ = open(kwargs['templates_dict']['file1']).read() # get template
    sql = task.render_template('', tmpl, kwargs)           # render it
    pp.pprint(sql)

Хотелось бы лучше найти решение!

Ответ 3

Недавно я столкнулся с той же проблемой и, наконец, решил ее. Решение @Ardan является правильным, но просто хочу повторить с более полным ответом с некоторыми подробностями о том, как Airflow работает для новичков.

Конечно, сначала вам нужно одно:

from airflow.operators.python_operator import PythonOperator

class SQLTemplatedPythonOperator(PythonOperator):

    # somehow ('.sql',) doesn't work but tuple of two works...
    template_ext = ('.sql','.abcdefg')

Предполагая, что у вас есть файл шаблона sql, как показано ниже:

# stored at path: $AIRFLOW_HOME/sql/some.sql
select {{some_params}} from my_table;

Сначала убедитесь, что вы добавили свою папку в путь поиска в параметрах dag.

Не проходите template_searchpath в args, а затем передавайте args в DAG !!!! Это не работает.

dag = DAG(
    dag_id= "some_name",
    default_args=args,
    schedule_interval="@once",
    template_searchpath='/Users/your_name/some_path/airflow_home/sql'
)

Тогда ваш оператор будет

SQLTemplatedPythonOperator(
        templates_dict={'query': 'some.sql'},
        op_kwargs={"args_directly_passed_to_your_function": "some_value"},
        task_id='dummy',
        params={"some_params":"some_value"},
        python_callable=your_func,
        provide_context=True,
        dag=dag,
    )

Ваша функция будет:

def your_func(args_directly_passed_to_your_function=None):
    query = context['templates_dict']['query']
    dome_some_thing(query)

Некоторые объяснения:

  1. Airflow использует значения из контекста для визуализации вашего шаблона. Чтобы вручную добавить его в контекст, вы можете использовать поле params, как указано выше.

  2. PythonOperator больше не использует расширение шаблона шаблона из поля template_ext, как, например, @Ardan. Исходный код здесь. Это требует только расширения от self.__ class __. Template_ext.

  3. Воздушный поток проходит через поле template_dict, и если значение.endswith(file_extension) == True, то оно отображает шаблон.

Ответ 4

Невозможно получить файл сценария, шаблон которого в python для работы (новый для python). Но пример с оператором bash следующий, может быть, это может дать вам несколько советов

from datetime import datetime
from airflow import DAG
from airflow.operators.bash_operator import BashOperator

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    #'start_date': airflow.utils.dates.days_ago(2),
    'email': ['[email protected]']}

dag = DAG('sr5', description='Simple tutorial DAG',
          schedule_interval='0 12 * * *',
          start_date=datetime(2017, 3, 20),
          catchup=False, #so that on scehduler restart, it doesn't try to catchup on all the missed runs
          template_searchpath=['/Users/my_name/Desktop/utils/airflow/resources'])

t1 = BashOperator(
    task_id='t1',
    depends_on_past=False,
    params={
        'ds1': 'hie'},
    bash_command="01.sh",
    dag=dag)

сценарий 01.sh выглядит следующим образом

#!/bin/sh

echo {{ ds }}
echo {{ params.ds1 }}

Это дает результат для выполнения теста

[2017-05-12 08: 31: 52,981] {bash_operator.py:91} INFO - выход:

[2017-05-12 08: 31: 52,984] {bash_operator.py:95} INFO - 2017-05-05

[2017-05-12 08: 31: 52,984] {bash_operator.py:95} INFO - hie