首页 > 解决方案 > 使用 Apache Airflow 的 SimpleHttpOperator 上传二进制数据的 PUT 请求

问题描述

我正在尝试使用 Apache Airflow 的SimpleHttpOperator上传一些二进制数据。
当使用 python 的请求时,我只需使用

requests.put(f'my.url.example',
              data=open('path_to_file, 'rb'), # parameter containing path to file
              auth=(username, password))

但是对于我的 Airflow 操作员,调用open()时文件的路径未正确呈现:

put_task = SimpleHttpOperator(
        task_id='put_task',
        http_conn_id='my_connection',
        endpoint="my.url.example/{{ ti.xcom_pull(task_ids='create_metadata', key='checksum') }}",
        method='PUT',
        headers = {"Content-Type": "application/json"},
        data=open(templ_local_filepath, 'rb'),          # not correctly rendered
        do_xcom_push=True,
        log_response=True,
    )

你建议我如何进行?谢谢

标签: pythonresthttpairflow

解决方案


我发现的一种解决方法是通过 a 来实现BashOperator(我也认为它更高效)。

put_task = BashOperator(
            task_id='put_task_',
            bash_command=rest_operations.templated_put,
            env={
                'basepath': basepath,
                'filename': filename,
                'checksum': "{{ ti.xcom_pull(task_ids='create_metadata', key='checksum') }}",
                'user': user,
                'password': password
            }
        )

谁的 bash 命令是

curl -s -o /dev/null -w "%{http_code}" \
        -H "Transfer-Encoding: chunked" \
        --upload-file $basepath/$filename \
        https://my.url.example/upload/data/$checksum \
        --user $user:$password

推荐阅读