我有两个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文件是否有技巧?
答案 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)
r.text是unicode中响应的内容,r.content是以字节为单位的响应内容