AirflowGCSToS3Operator:传输只有一个文件且需要指定文件名
创始人
2024-08-02 03:30:19
0

可以通过自定义 Operator 来实现只传输一个文件并指定文件名。首先需要继承 GCSToS3Operator,然后重写 execute 函数,在函数中调用 GCSHook 和 S3Hook 进行文件传输,同时指定目标 S3 上的文件名。

示例代码如下所示:

from airflow.contrib.operators.gcs_to_s3 import GCSToS3Operator
from airflow.providers.amazon.aws.hooks.s3 import S3Hook
from airflow.providers.google.cloud.hooks.gcs import GCSHook

class GCSFileToS3Operator(GCSToS3Operator):
    
    def __init__(
        self,
        source_bucket: str,
        source_object: str,
        destination_bucket: str,
        destination_object: str,
        **kwargs,
    ):
        super().__init__(
            source_bucket=source_bucket,
            source_object=source_object,
            destination_bucket=destination_bucket,
            destination_object=destination_object,
            **kwargs,
        )
        self.source_bucket = source_bucket
        self.source_object = source_object
        self.destination_bucket = destination_bucket
        self.destination_object = destination_object

    def execute(self, context):
        gcs_hook = GCSHook()
        s3_hook = S3Hook(aws_conn_id=self.aws_conn_id)

        # Download the file from GCS to local
        tmp_file = self._build_gcs_uri(self.source_bucket, self.source_object)
        self.log.info("Downloading from %s", tmp_file)
        with NamedTemporaryFile() as f:
            gcs_hook.download(bucket_name=self.source_bucket, object_name=self.source_object, filename=f.name)

            f.seek(0)

            # Upload the file to S3
            s3_hook.load_file(
                filename=f.name,
                key=self.destination_object,
                bucket_name=self.destination_bucket
            )

        self.log.info("File has been uploaded to %s/%s", self.destination_bucket, self.destination_object)

在 DAG 文件中使用自定义 Operator,只需要指定 GCS 上的文件路径和 S3 上的文件名即可:

from datetime import datetime
from airflow import DAG
from

相关内容

热门资讯

安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
避免在粘贴双引号时向VS 20... 在粘贴双引号时向VS 2022添加反斜杠的问题通常是由于编辑器的自动转义功能引起的。为了避免这个问题...
Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
omi系统和安卓系统哪个好,揭... OMI系统和安卓系统哪个好?这个问题就像是在问“苹果和橘子哪个更甜”,每个人都有自己的答案。今天,我...
原生ios和安卓系统,原生对比... 亲爱的读者们,你是否曾好奇过,为什么你的iPhone和安卓手机在操作体验上有着天壤之别?今天,就让我...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
Alertmanager在pr... 首先,在Prometheus配置文件中,确保Alertmanager URL已正确配置。例如:ale...