Python 烧瓶:返回的文件不可读



在python flask中实现rest API时,我使用了几个选项来返回文件(任何类型(,读取它并将其保存到请求的本地存储库,但遇到了多个错误,如下所示:

案例1:

def download_file(): return send_file('any_file.pdf') r = requests.get(url = 'http://localhost:5000/download').read()

已响应错误响应对象没有属性读取/文本/内容

案例2:

def download_file(): file = open('any_file.pdf','r').read() return file r = requests.get(url = 'http://localhost:5000/download')

已响应错误返回不接受此

那么我该怎么做,因为烧瓶不允许返回没有响应对象的文件,并且响应对象不可读,不支持直接保存该文件。

Case 1中的 Flask服务器代码是正确的。 一个更完整的示例:

@app.route('/download')
def download_file():
# Some logic here
send_file('any_file.pdf')

但是,requests.get返回的Response对象没有read方法。 正确的方法是使用:

Response.content:响应的内容,以字节为单位。

因此,客户端代码应该是:

r = requests.get('http://localhost:5000/download')
bytes = r.content
# Now do something with bytes, for example save it:
with open('downloaded_file.ext', 'wb') as f:
f.write(bytes)

最新更新