使用Python请求发送和接收Zip文件

时间:2016-03-02 22:18:04

标签: python zip python-requests

我有两个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文件是否有技巧?

1 个答案:

答案 0 :(得分:0)

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是以字节为单位的响应内容