-
Notifications
You must be signed in to change notification settings - Fork 16.4k
Add FTPFileTransmitOperator
#26974
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Add FTPFileTransmitOperator
#26974
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
0a79cb3
Add FTP Operator
RachitSharma2001 f7ea904
Merge branch 'main' into main
RachitSharma2001 307d31a
Added Requested Changes
RachitSharma2001 15adeae
Added Example FTP Dags
RachitSharma2001 c349edf
Merge branch 'main' into main
RachitSharma2001 bb81cdd
Merge branch 'main' into main
RachitSharma2001 d57ec9d
Merge branch 'main' into main
RachitSharma2001 7f69c01
Merge branch 'main' into main
jedcunningham a49143f
Fixed Static Check Errors
RachitSharma2001 a15d640
Rename to FTPFileTransmitOperator
RachitSharma2001 ad497ce
Reformat Example DAG to AIP-47
RachitSharma2001 b6d4b28
Fix Build Docs Errors
RachitSharma2001 8c7d884
Merge branch 'main' into main
RachitSharma2001 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| # Licensed to the Apache Software Foundation (ASF) under one | ||
| # or more contributor license agreements. See the NOTICE file | ||
| # distributed with this work for additional information | ||
| # regarding copyright ownership. The ASF licenses this file | ||
| # to you under the Apache License, Version 2.0 (the | ||
| # "License"); you may not use this file except in compliance | ||
| # with the License. You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, | ||
| # software distributed under the License is distributed on an | ||
| # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| # KIND, either express or implied. See the License for the | ||
| # specific language governing permissions and limitations | ||
| # under the License. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,132 @@ | ||
| # | ||
| # Licensed to the Apache Software Foundation (ASF) under one | ||
| # or more contributor license agreements. See the NOTICE file | ||
| # distributed with this work for additional information | ||
| # regarding copyright ownership. The ASF licenses this file | ||
| # to you under the Apache License, Version 2.0 (the | ||
| # "License"); you may not use this file except in compliance | ||
| # with the License. You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, | ||
| # software distributed under the License is distributed on an | ||
| # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| # KIND, either express or implied. See the License for the | ||
| # specific language governing permissions and limitations | ||
| # under the License. | ||
| """This module contains FTP operator.""" | ||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| from pathlib import Path | ||
| from typing import Any, Sequence | ||
|
|
||
| from airflow.compat.functools import cached_property | ||
| from airflow.models import BaseOperator | ||
| from airflow.providers.ftp.hooks.ftp import FTPHook | ||
|
|
||
|
|
||
| class FTPOperation: | ||
| """Operation that can be used with FTP""" | ||
|
|
||
| PUT = "put" | ||
| GET = "get" | ||
|
|
||
|
|
||
| class FTPFileTransmitOperator(BaseOperator): | ||
| """ | ||
| FTPFileTransmitOperator for transferring files from remote host to local or vice a versa. | ||
| This operator uses an FTPHook to open ftp transport channel that serve as basis | ||
| for file transfer. | ||
|
|
||
| .. seealso:: | ||
| For more information on how to use this operator, take a look at the guide: | ||
| :ref:`howto/operator:FTPFileTransmitOperator` | ||
|
|
||
| :param ftp_conn_id: :ref:`ftp connection id<howto/connection:ftp>` | ||
| from airflow Connections. | ||
| :param local_filepath: local file path to get or put. (templated) | ||
| :param remote_filepath: remote file path to get or put. (templated) | ||
| :param operation: specify operation 'get' or 'put', defaults to put | ||
| :param create_intermediate_dirs: create missing intermediate directories when | ||
| copying from remote to local and vice-versa. Default is False. | ||
|
|
||
| Example: The following task would copy ``file.txt`` to the remote host | ||
| at ``/tmp/tmp1/tmp2/`` while creating ``tmp``,``tmp1`` and ``tmp2`` if they | ||
| don't exist. If the ``create_intermediate_dirs`` parameter is not passed it would error | ||
| as the directory does not exist. :: | ||
|
|
||
| put_file = FTPFileTransmitOperator( | ||
| task_id="test_ftp", | ||
| ftp_conn_id="ftp_default", | ||
| local_filepath="/tmp/file.txt", | ||
| remote_filepath="/tmp/tmp1/tmp2/file.txt", | ||
| operation="put", | ||
| create_intermediate_dirs=True, | ||
| dag=dag | ||
| ) | ||
| """ | ||
|
|
||
| template_fields: Sequence[str] = ("local_filepath", "remote_filepath") | ||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| ftp_conn_id: str = "ftp_default", | ||
| local_filepath: str | list[str], | ||
| remote_filepath: str | list[str], | ||
| operation: str = FTPOperation.PUT, | ||
| create_intermediate_dirs: bool = False, | ||
| **kwargs, | ||
| ) -> None: | ||
| super().__init__(**kwargs) | ||
| self.ftp_conn_id = ftp_conn_id | ||
| self.operation = operation | ||
| self.create_intermediate_dirs = create_intermediate_dirs | ||
|
|
||
| if isinstance(local_filepath, str): | ||
| self.local_filepath = [local_filepath] | ||
| else: | ||
| self.local_filepath = local_filepath | ||
|
|
||
| if isinstance(remote_filepath, str): | ||
| self.remote_filepath = [remote_filepath] | ||
| else: | ||
| self.remote_filepath = remote_filepath | ||
|
|
||
| if len(self.local_filepath) != len(self.remote_filepath): | ||
| raise ValueError( | ||
| f"{len(self.local_filepath)} paths in local_filepath " | ||
| f"!= {len(self.remote_filepath)} paths in remote_filepath" | ||
| ) | ||
|
|
||
| if self.operation.lower() not in [FTPOperation.GET, FTPOperation.PUT]: | ||
| raise TypeError( | ||
| f"Unsupported operation value {self.operation}, " | ||
| f"expected {FTPOperation.GET} or {FTPOperation.PUT}." | ||
| ) | ||
|
|
||
| @cached_property | ||
| def hook(self) -> FTPHook: | ||
| """Create and return an FTPHook.""" | ||
| return FTPHook(ftp_conn_id=self.ftp_conn_id) | ||
|
|
||
| def execute(self, context: Any) -> str | list[str] | None: | ||
| file_msg = None | ||
| for local_filepath, remote_filepath in zip(self.local_filepath, self.remote_filepath): | ||
| if self.operation.lower() == FTPOperation.GET: | ||
| local_folder = os.path.dirname(local_filepath) | ||
| if self.create_intermediate_dirs: | ||
| Path(local_folder).mkdir(parents=True, exist_ok=True) | ||
| file_msg = f"from {remote_filepath} to {local_filepath}" | ||
| self.log.info("Starting to transfer %s", file_msg) | ||
| self.hook.retrieve_file(remote_filepath, local_filepath) | ||
| else: | ||
| remote_folder = os.path.dirname(remote_filepath) | ||
| if self.create_intermediate_dirs: | ||
| self.hook.create_directory(remote_folder) | ||
| file_msg = f"from {local_filepath} to {remote_filepath}" | ||
| self.log.info("Starting to transfer file %s", file_msg) | ||
| self.hook.store_file(remote_filepath, local_filepath) | ||
| return self.local_filepath |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| .. Licensed to the Apache Software Foundation (ASF) under one | ||
| or more contributor license agreements. See the NOTICE file | ||
| distributed with this work for additional information | ||
| regarding copyright ownership. The ASF licenses this file | ||
| to you under the Apache License, Version 2.0 (the | ||
| "License"); you may not use this file except in compliance | ||
| with the License. You may obtain a copy of the License at | ||
|
|
||
| .. http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| .. Unless required by applicable law or agreed to in writing, | ||
| software distributed under the License is distributed on an | ||
| "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| KIND, either express or implied. See the License for the | ||
| specific language governing permissions and limitations | ||
| under the License. | ||
|
|
||
|
|
||
|
|
||
| .. _howto/operator:FTPFileTransmitOperator: | ||
|
|
||
| FTPFileTransmitOperator | ||
| ========================= | ||
|
|
||
|
|
||
| Use the FTPFileTransmitOperator to get or | ||
| pull files to/from an FTP server. | ||
|
|
||
| Using the Operator | ||
| ^^^^^^^^^^^^^^^^^^ | ||
|
|
||
| For parameter definition take a look at :class:`~airflow.providers.ftp.operators.FTPFileTransmitOperator`. | ||
|
|
||
| The below example shows how to use the FTPFileTransmitOperator to transfer a locally stored file to a remote FTP Server: | ||
|
|
||
| .. exampleinclude:: /../../tests/system/providers/ftp/example_ftp.py | ||
| :language: python | ||
| :dedent: 4 | ||
| :start-after: [START howto_operator_ftp_put] | ||
| :end-before: [END howto_operator_ftp_put] | ||
|
|
||
| The below example shows how to use the FTPFileTransmitOperator to pull a file from a remote FTP Server. | ||
|
|
||
| .. exampleinclude:: /../../tests/system/providers/ftp/example_ftp.py | ||
| :language: python | ||
| :dedent: 4 | ||
| :start-after: [START howto_operator_ftp_get] | ||
| :end-before: [END howto_operator_ftp_get] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| # Licensed to the Apache Software Foundation (ASF) under one | ||
| # or more contributor license agreements. See the NOTICE file | ||
| # distributed with this work for additional information | ||
| # regarding copyright ownership. The ASF licenses this file | ||
| # to you under the Apache License, Version 2.0 (the | ||
| # "License"); you may not use this file except in compliance | ||
| # with the License. You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, | ||
| # software distributed under the License is distributed on an | ||
| # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| # KIND, either express or implied. See the License for the | ||
| # specific language governing permissions and limitations | ||
| # under the License. |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added an ftp_default connection, as it previously did not exist.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Even though the unit tests no longer use a local FTP Server, I still think that having this FTP Default connection would be useful, as without this, defining the following piece of code will throw an error indicating that the "connection with id 'ftp_default' does not exist":
hook = FTPHook()