2016-03-02 83 views
0

我有兩個REST(Flask)API。第一個API從本地磁盤讀取一個zip文件,並將其返回到POST請求中。第二個API調用第一個API,並將該文件寫入本地。使用Python請求發送和接收Zip文件

對編碼有點無知,我遇到了問題。

@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')),並且在文件寫入然後工作了,我在嘗試unzip它在Linux中收到以下錯誤:

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) 

有一招,在休息與發送zip文件要求?

回答

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是在該響應的內容字節

相關問題