【问题标题】:Python Flask : Returned file is not readablePython Flask:返回的文件不可读
【发布时间】:2020-05-12 00:47:49
【问题描述】:

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

案例一:

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')

已响应错误返回不接受此

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

【问题讨论】:

  • 我想,你错过了方案 http:// 0.0.0.0:5000/download
  • 是的,你是对的。现已编辑

标签: python flask response flask-restful sendfile


【解决方案1】:

Case 1 中的 Flask server 代码是正确的。一个更完整的例子:

@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)

【讨论】:

  • 我会检查这个。
  • 这对我有用,但文件内容未正确存储在存储中。
  • @ShahMuhammadTalha 抱歉,您能否扩展一下“未正确存储在存储中”...您看到了什么行为?
猜你喜欢
  • 2021-05-11
  • 2012-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-27
  • 1970-01-01
  • 2012-12-26
  • 1970-01-01
相关资源
最近更新 更多