Python - 在 FTP 中按 block 上传内存中文件(由 API 调用生成)

标签 python ftp sftp paramiko ftplib

我需要能够在 Python 中通过 FTP 和 SFTP 上传文件,但有一些不那么常见的限制。

  1. 文件不得写入磁盘。

  2. 文件的生成方式是调用 API 并将 JSON 格式的响应写入文件。

  3. 对 API 进行了多次调用。不可能通过一次 API 调用来检索整个结果。

  4. 我无法通过执行所需的多个调用并在每个调用中附加直到将整个文件存储在内存中来将完整结果存储在字符串变量中。文件可能很大并且存在内存资源限制。应发送每个 block 并释放内存。

这里是我想要的一些示例代码:

def chunks_generator():
    range_list = range(0, 4000, 100)
    for i in range_list:
        data_chunk = requests.get(url=someurl, url_parameters={'offset':i, 'limit':100})
        yield str(data_chunk)

def upload_file():
    chunks_generator = chunks_generator()
    for chunk in chunks_generator:
        data_chunk= chunk
        chunk_io = io.BytesIO(data_chunk)
        ftp = FTP(self.host)
        ftp.login(user=self.username, passwd=self.password)
        ftp.cwd(self.remote_path)
        ftp.storbinary("STOR " + "myfilename.json", chunk_io)

我只想要一个附加了所有 block 的文件。 我已经拥有并且有效的方法是,如果我将整个文件存储在内存中并像这样立即发送它:

string_io = io.BytesIO(all_chunks_together_in_one_string)
ftp = FTP(self.host)
ftp.login(user=self.username, passwd=self.password)
ftp.cwd(self.remote_path)
ftp.storbinary("STOR " + "myfilename.json", string_io )

奖金

我在 ftplib 中需要它,但在 Paramiko 中也需要它来进行 SFTP。如果有任何其他库可以更好地工作,我是开放的。

如果我需要压缩文件怎么办?我可以压缩每个 block 并一次发送压缩 block 吗?

最佳答案

您可以实现类似文件的类,在调用 .read(blocksize) 方法时从 requests 对象检索数据。

类似这样的东西(未经测试):

class ChunksGenerator:
    i = 0
    requests = None

    def __init__(self, requests)
        self.requests = requests

    def read(self, blocksize):
        # TODO: somehow detect end-of-file and return false in that case
        buf = requests.get(
                  url=someurl, url_parameters={'offset':self.i, 'limit':blocksize})
        self.i += blocksize
        return buf

generator = ChunksGenerator(requests)
ftp.storbinary("STOR " + "myfilename.json", generator)
<小时/>

使用Paramiko,您可以使用与 SFTPClient.putfo method 相同的类.

关于Python - 在 FTP 中按 block 上传内存中文件(由 API 调用生成),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51632215/

相关文章:

maven-2 - 使用 Maven 2 将程序集部署到 FTP 服务器

python - 带有 key 和用户名/密码的 Paramiko SFTP - "Oops, unhandled type 3"

python - Flask 安装不正常

python - 如何根据元组中的值删除列表中的元组?

python - 在 python 中从模板文件和 csv 数据生成输出文件

Python "callable"属性(伪属性)

java - 使用 apache commons-net FTPClient 传输原始二进制文件?

ftp - 在FTP中,如何将远程文件复制到其他目录

c# - SSH.NET SocketException尝试以其访问权限禁止的方式访问套接字

unix - "mount --bind"用户目录消失