[AirFlow]AirFlow使用指南三 第一个DAG示例

经过前两篇文章的简单介绍之后,我们安装了自己的AirFlow以及简单了解了DAG的定义文件.现在我们要实现自己的一个DAG.

1. 启动Web服务器

使用如下命令启用:

airflow webserver

现在可以通过将浏览器导航到启动Airflow的主机上的8080端口来访问Airflow UI,例如:http://localhost:8080/admin/

img

备注

Airflow附带了许多示例DAG。 请注意,在你自己的`dags_folder`中至少有一个DAG定义文件之前,这些示例可能无法正常工作。你可以通过更改`airflow.cfg`中`load_examples`设置来隐藏示例DAG。

2. 第一个AirFlow DAG

现在一切都准备好了,我们开始写一些代码,来实现我们的第一个DAG。 我们将首先创建一个Hello World工作流程,其中除了向日志发送"Hello world!"之外什么都不做。

创建你的dags_folder那就是你的DAG定义文件存储目录---$AIRFLOW_HOME/dags。在该目录中创建一个名为hello_world.py的文件。

AIRFLOW_HOME
├── airflow.cfg
├── airflow.db
├── airflow-webserver.pid
├── dags
│   ├── hello_world.py
│   └── hello_world.pyc
└── unittests.cfg

将以下代码添加到dags/hello_world.py中:

# -*- coding: utf-8 -*-

import airflow
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.python_operator import PythonOperator
from datetime import timedelta

#-------------------------------------------------------------------------------
# these args will get passed on to each operator
# you can override them on a per-task basis during operator initialization

default_args = {
    'owner': 'jifeng.si',
    'depends_on_past': False,
    'start_date': airflow.utils.dates.days_ago(2),
    'email': ['1203745031@qq.com'],
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5),
    # 'queue': 'bash_queue',
    # 'pool': 'backfill',
    # 'priority_weight': 10,
    # 'end_date': datetime(2016, 1, 1),
    # 'wait_for_downstream': False,
    # 'dag': dag,
    # 'adhoc':False,
    # 'sla': timedelta(hours=2),
    # 'execution_timeout': timedelta(seconds=300),
    # 'on_failure_callback': some_function,
    # 'on_success_callback': some_other_function,
    # 'on_retry_callback': another_function,
    # 'trigger_rule': u'all_success'
}

#-------------------------------------------------------------------------------
# dag

dag = DAG(
    'example_hello_world_dag',
    default_args=default_args,
    description='my first DAG',
    schedule_interval=timedelta(days=1))

#-------------------------------------------------------------------------------
# first operator

date_operator = BashOperator(
    task_id='date_task',
    bash_command='date',
    dag=dag)

#-------------------------------------------------------------------------------
# second operator

sleep_operator = BashOperator(
    task_id='sleep_task',
    depends_on_past=False,
    bash_command='sleep 5',
    dag=dag)

#-------------------------------------------------------------------------------
# third operator

def print_hello():
    return 'Hello world!'

hello_operator = PythonOperator(
    task_id='hello_task',
    python_callable=print_hello,
    dag=dag)

#-------------------------------------------------------------------------------
# dependencies

sleep_operator.set_upstream(date_operator)
hello_operator.set_upstream(date_operator)

该文件创建一个简单的DAG,只有三个运算符,两个BaseOperator(一个打印日期一个休眠5秒),另一个为PythonOperator在执行任务时调用print_hello函数。

3. 测试代码

使用如下命令测试一下我们写的代码的正确性:

python ~/opt/airflow/dags/hello_world.py

如果你的脚本没有抛出异常,这意味着你代码中没有错误,并且你的Airflow环境是健全的。

下面测试一下我们的DAG中的Task.使用如下命令查看我们example_hello_world_dagDAG下有什么Task:

xiaosi@yoona:~$ airflow list_tasks example_hello_world_dag
[2017-08-03 11:41:57,097] {__init__.py:57} INFO - Using executor SequentialExecutor
[2017-08-03 11:41:57,220] {driver.py:120} INFO - Generating grammar tables from /usr/lib/python2.7/lib2to3/Grammar.txt
[2017-08-03 11:41:57,241] {driver.py:120} INFO - Generating grammar tables from /usr/lib/python2.7/lib2to3/PatternGrammar.txt
[2017-08-03 11:41:57,490] {models.py:167} INFO - Filling up the DagBag from /home/xiaosi/opt/airflow/dags
date_task
hello_task
sleep_task

可以看到我们有三个Task:

date_task
hello_task
sleep_task

下面分别测试一下这几个Task:

(1) 测试date_task

xiaosi@yoona:~$ airflow test example_hello_world_dag date_task 20170803
...
--------------------------------------------------------------------------------
Starting attempt 1 of 2
--------------------------------------------------------------------------------

[2017-08-03 11:44:02,248] {models.py:1342} INFO - Executing <Task(BashOperator): date_task> on 2017-08-03 00:00:00
[2017-08-03 11:44:02,258] {bash_operator.py:71} INFO - tmp dir root location:
/tmp
[2017-08-03 11:44:02,259] {bash_operator.py:80} INFO - Temporary script location :/tmp/airflowtmpxh6da9//tmp/airflowtmpxh6da9/date_tasktQQB0V
[2017-08-03 11:44:02,259] {bash_operator.py:81} INFO - Running command: date
[2017-08-03 11:44:02,264] {bash_operator.py:90} INFO - Output:
[2017-08-03 11:44:02,265] {bash_operator.py:94} INFO - 2017年 08月 03日 星期四 11:44:02 CST
[2017-08-03 11:44:02,266] {bash_operator.py:97} INFO - Command exited with return code 0

(2) 测试hello_task

xiaosi@yoona:~$ airflow test example_hello_world_dag hello_task 20170803
...
--------------------------------------------------------------------------------
Starting attempt 1 of 2
--------------------------------------------------------------------------------

[2017-08-03 11:45:29,546] {models.py:1342} INFO - Executing <Task(PythonOperator): hello_task> on 2017-08-03 00:00:00
[2017-08-03 11:45:29,551] {python_operator.py:81} INFO - Done. Returned value was: Hello world!

(3) 测试sleep_task

xiaosi@yoona:~$ airflow test example_hello_world_dag sleep_task 20170803
...
--------------------------------------------------------------------------------
Starting attempt 1 of 2
--------------------------------------------------------------------------------

[2017-08-03 11:46:23,970] {models.py:1342} INFO - Executing <Task(BashOperator): sleep_task> on 2017-08-03 00:00:00
[2017-08-03 11:46:23,981] {bash_operator.py:71} INFO - tmp dir root location:
/tmp
[2017-08-03 11:46:23,983] {bash_operator.py:80} INFO - Temporary script location :/tmp/airflowtmpsuamQx//tmp/airflowtmpsuamQx/sleep_taskuKYlrh
[2017-08-03 11:46:23,983] {bash_operator.py:81} INFO - Running command: sleep 5
[2017-08-03 11:46:23,988] {bash_operator.py:90} INFO - Output:
[2017-08-03 11:46:28,990] {bash_operator.py:97} INFO - Command exited with return code 0

如果没有问题,我们就可以运行我们的DAG了.

4. 运行DAG

为了运行你的DAG,打开另一个终端,并通过如下命令来启动Airflow调度程序:

airflow scheduler

备注

调度程序将发送任务进行执行。默认Airflow设置依赖于一个名为`SequentialExecutor`的执行器,它由调度程序自动启动。在生产中,你可以使用更强大的执行器,如`CeleryExecutor`。

当你在浏览器中重新加载Airflow UI时,应该会在Airflow UI中看到你的hello_world DAG。

img

为了启动DAG Run,首先打开工作流(off键),然后单击Trigger Dag按钮(Links 第一个按钮),最后单击Graph View按钮(Links 第三个按钮)以查看运行进度:

img

你可以重新加载图形视图,直到两个任务达到状态成功。完成后,你可以单击hello_task,然后单击View Log查看日志。如果一切都按预期工作,日志应该显示一些行,其中之一是这样的:

...
[2017-08-03 09:46:43,213] {base_task_runner.py:95} INFO - Subtask: --------------------------------------------------------------------------------
[2017-08-03 09:46:43,213] {base_task_runner.py:95} INFO - Subtask: Starting attempt 1 of 2
[2017-08-03 09:46:43,214] {base_task_runner.py:95} INFO - Subtask: --------------------------------------------------------------------------------
[2017-08-03 09:46:43,214] {base_task_runner.py:95} INFO - Subtask:
[2017-08-03 09:46:43,228] {base_task_runner.py:95} INFO - Subtask: [2017-08-03 09:46:43,228] {models.py:1342} INFO - Executing <Task(PythonOperator): hello_task> on 2017-08-03 09:45:49.070859
[2017-08-03 09:46:43,236] {base_task_runner.py:95} INFO - Subtask: [2017-08-03 09:46:43,235] {python_operator.py:81} INFO - Done. Returned value was: Hello world!
[2017-08-03 09:46:47,378] {jobs.py:2083} INFO - Task exited with return code 0
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/SunnyYoona/article/details/76615699
### 回答1: Airflow DAG 网络接口请求,并且把请求结果写入DB的示例可以这样实现:定义一个任务,使用 Airflow 的 Operator 来完成网络接口的 HTTP 请求,并使用 Hook 来连接到你的 DB,最后将结果写入 DB。 ### 回答2: Airflow是一个开源的任务调度平台,可以实现可编程的工作流程。它的核心概念是Directed Acyclic Graphs(DAGs),以DAG作为任务的描述单位。在Airflow中,可以使用DAG来描述一个任务的依赖关系,并定义其执行逻辑。 下面是一个使用Airflow简单实现网络接口请求并将结果写入数据库的示例: 1. 首先,在AirflowDAG目录中创建一个Python文件,命名为"my_dag.py"。 2. 在文件中导入所需要的库和模块,如下: ```python import requests from airflow import DAG from airflow.operators.python_operator import PythonOperator from datetime import datetime ``` 3. 在文件中定义一个函数,用于执行网络接口请求并将结果写入数据库,例如: ```python def request_and_write_to_db(): url = 'http://example.com/api/endpoint' # 替换为你要请求的接口地址 response = requests.get(url) data = response.json() # 将数据写入数据库,这里使用示例的MySQL数据库 # 假设你已经定义了数据库连接和表结构 conn = MySQLConnection(user='your_username', password='your_password', host='your_host', database='your_database') cursor = conn.cursor() cursor.execute("INSERT INTO your_table (column1, column2) VALUES (%s, %s)", (data['value1'], data['value2'])) conn.commit() cursor.close() conn.close() ``` 4. 在文件中创建一个AirflowDAG对象,并定义其属性和任务,如下: ```python dag = DAG('request_and_save_to_db', description='A simple Airflow DAG to request a web API and save the result to a database', schedule_interval='0 0 * * *', start_date=datetime(2022, 1, 1), catchup=False) task = PythonOperator(task_id='request_save_task', python_callable=request_and_write_to_db, dag=dag) # 设置任务的依赖关系,这里没有依赖其他任务 task ``` 5. 保存文件并运行Airflow的调度器,DAG将根据定义的调度间隔定期执行任务。 这个示例中,我们定义了一个名为"request_and_save_to_db"的DAG,它会在每天的午夜运行一次任务。 在任务中,我们使用了PythonOperator来执行函数"request_and_write_to_db"。在函数中,我们发送了一个GET请求到指定的URL,并将返回的数据写入数据库。 这只是一个简单的示例,你可以根据自己的需求和具体接口进行更加复杂的处理和逻辑设计。 ### 回答3: Airflow是一个开源的任务调度和工作流管理平台,可以方便地将任务组织成有向无环图(DAG)进行调度和监控。在Airflow中,我们可以使用Python编写DAG描述文件,通过定义任务之间的依赖关系和执行逻辑来实现任务的调度。 要实现网络接口请求并将结果写入数据库的示例,我们可以使用Airflow的PythonOperator来执行这个任务。首先,我们需要导入所需的库和模块,如requests和sqlalchemy。 ```python from datetime import datetime from airflow import DAG from airflow.operators.python_operator import PythonOperator import requests from sqlalchemy import create_engine def get_data(): url = 'https://example.com/api/data' # 网络接口请求的URL response = requests.get(url) # 发送GET请求 data = response.json() # 解析响应的JSON数据 return data def write_to_db(): data = get_data() engine = create_engine('postgresql://username:password@localhost/database') # 数据库连接信息 conn = engine.connect() # 将数据写入数据库表中 # 具体的写入逻辑需根据数据库结构进行实现 conn.execute("INSERT INTO table_name (column1, column2, ...) VALUES (:value1, :value2, ...)", data) conn.close() # 定义DAG dag = DAG( dag_id='example_dag', schedule_interval='@daily', start_date=datetime(2022, 1, 1) ) # 定义任务 get_data_task = PythonOperator( task_id='get_data', python_callable=get_data, dag=dag ) write_to_db_task = PythonOperator( task_id='write_to_db', python_callable=write_to_db, dag=dag ) # 设置任务依赖关系 get_data_task >> write_to_db_task ``` 上述示例中,get_data函数用于发送网络接口请求并解析响应数据,write_to_db函数用于将获取到的数据写入数据库表中。我们首先使用PythonOperator定义两个任务get_data_task和write_to_db_task,分别指定对应的Python函数作为任务的执行逻辑。然后通过设置任务的依赖关系get_data_task >> write_to_db_task来定义任务的执行顺序。 最后,我们以每天执行一次的方式定义DAG的调度频率,并指定DAG的启动日期为2022年1月1日。可以根据实际需求进行调整和修改。 注意:在实际使用中,需要根据具体的网络接口和数据库结构进行适当的修改和优化,确保代码的正确性和性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值