Airflow提供了一个名为HttpHook的HTTP操作器,可以用来向API发送HTTP请求。此外,还有一个名为HttpSensor的传感器,可以用来等待特定的HTTP响应。
以下是一份示例代码,展示了如何在Airflow中使用HttpHook和HttpSensor:
http模块,可以通过运行以下命令来安装它:pip install apache-airflow[http]
http_example.py),并导入所需的模块:from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from airflow.contrib.hooks.http_hook import HttpHook
from airflow.contrib.sensors.http_sensor import HttpSensor
from datetime import datetime, timedelta
HttpHook对象,并使用它来发送HTTP请求。下面的示例代码展示了如何发送一个GET请求:def send_http_request():
    http_hook = HttpHook(method='GET', http_conn_id='http_conn')
    response = http_hook.run(endpoint='https://api.example.com')
    print(response.text)
http_task = PythonOperator(
    task_id='send_http_request',
    python_callable=send_http_request,
    dag=dag
)
HttpSensor对象,并使用它来等待特定的HTTP响应。下面的示例代码展示了如何等待一个状态码为200的响应:def check_http_response():
    http_sensor = HttpSensor(
        task_id='check_http_response',
        http_conn_id='http_conn',
        endpoint='https://api.example.com',
        request_params={'method': 'GET'},
        response_check=lambda response: response.status_code == 200,
        poke_interval=60,
        timeout=600
    )
    http_sensor.execute(context={})
sensor_task = PythonOperator(
    task_id='check_http_response',
    python_callable=check_http_response,
    dag=dag
)
请注意,上述示例中的http_conn_id参数是指向Airflow连接的连接ID,应该在Airflow的Web界面中进行配置。
通过以上步骤,您就可以在Airflow中使用HttpHook和HttpSensor来进行HTTP操作和传感器了。您可以根据需要自定义请求和响应的内容。