【问题标题】:Trouble Transferring data from FTP server to S3 via stream using Python使用 Python 通过流将数据从 FTP 服务器传输到 S3 时遇到问题
【发布时间】:2016-12-15 19:20:43
【问题描述】:

我希望将文件夹的内容从 ftp 服务器传输到 s3 中的存储桶,而不写入磁盘。目前,s3 正在获取文件夹中所有文件的名称,但没有获取实际数据。文件夹中的每个文件只有几个字节。我不太清楚为什么它没有上传整个文件。

from ftplib import FTP
import io 
import boto3


s3= boto3.resource('s3')

ftp = FTP('ftp.ncbi.nlm.nih.gov')
ftp.login()
ftp.cwd('pubchem/RDF/descriptor/compound')

address =  'ftp.ncbi.nlm.nih.gov/pubchem/RDF/descriptor/compound/'

filelist = ftp.nlst()

for x in range(0, len(filelist)-1):
    myfile = io.BytesIO()
    filename = 'RETR ' + filelist[x]
    resp = ftp.retrbinary(filename, myfile.write)
    myfile.seek(0)
    path = address + filelist[x]
    #putting file on s3
    s3.Object(s3bucketname, path).put(Body = resp)


ftp.quit()

有什么方法可以确保整个文件都上传了吗?

【问题讨论】:

    标签: python amazon-s3 ftp


    【解决方案1】:

    我们可以使用 Python 通过流将数据从 FTP 服务器传输到 S3。数据不会下载到 AWS Lambda 的 /tmp 位置。它将直接将数据从 FTP 流式传输到 S3 存储桶。

    from ftplib import FTP
    import s3fs
    
    def lambda_handler(event, context):
        file_name = "test.txt" #file name in ftp
        s3 = s3fs.S3FileSystem(anon=False)
        ftp_path = "<ftp_path>"
        s3_path = "s3-dev" #S3 bucket name
    
    with FTP("<ftp_server>") as ftp:
        ftp.login()
        ftp.cwd(ftp_path)
        ftp.retrbinary('RETR ' + file_name, s3.open("{}/{}".format(s3_path, file_name), 'wb').write)
    

    【讨论】:

      【解决方案2】:

      当我更改 .put() 以从保存文件的位置读取实际文件时,我遇到了同样的问题并让它工作。所以像这样的事情,你没有直接处理 resp

      s3.Object(s3Bucketname, filename).put(Body=open(filename, 'rb'))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多