【问题标题】:Sending and Receving Zip files with Python Requests使用 Python 请求发送和接收 Zip 文件
【发布时间】:2025-12-13 01:45:01
【问题描述】:

我有两个 REST (Flask) API。第一个 API 从本地磁盘读取一个 zip 文件,并在 POST 请求中返回它。第二个 API 调用第一个 API,并将文件写入本地。

由于对编码有点无知,我遇到了问题。

@app.route('/push/', methods=['POST'])
def push():
    with open('/path/to/zip_file.zip', 'r') as f:
        foo = f.read()
    return foo

@app.route('/pull/', methods=['POST'])
def pull():
    url = 'https://myhost.com/push/'
    r = requests.post(url, verify=False)
    with open(/new/path/to/zip_file.zip', 'w') as f:
        # f.write(r.text)  # this fails with UnicodeEncodeDecode error
        f.write(r.text.encode('utf-8'))  # this doesn't fail, but I can't unzip the resulting file

在第二个 API 中,我最初尝试 f.write(r.text),但失败了:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 63-64: ordinal not in range(128)

我尝试在谷歌搜索后将其更改为f.write(r.text.encode('utf-8')),然后在写入文件时,我在 Linux 中尝试unzip 时收到以下错误:

error [OWBMaster_0.1.zip]:  missing 3112778871 bytes in zipfile
  (attempting to process anyway)
error [OWBMaster_0.1.zip]:  start of central directory not found;
  zipfile corrupt.
  (please check that you have transferred or created the zipfile in the
  appropriate BINARY mode and that you have compiled UnZip properly)

通过 REST 发送带有请求的 zip 文件有技巧吗?

【问题讨论】:

    标签: python zip python-requests


    【解决方案1】:

    r.text 更改为 r.content 修复了此问题:

    @app.route('/pull/', methods=['POST'])
    def pull():
        url = 'https://myhost.com/push/'
        r = requests.post(url, verify=False)
        with open(/new/path/to/zip_file.zip', 'w') as f:
        # f.write(r.content)
    

    来自this question

    r.text 是响应的 unicode 内容,r.content 是响应的内容,以字节为单位

    【讨论】: