python - 将文件返回到客户端而不保存在从 GCP 云存储下载的服务器端
问题描述
我正在处理 Flask 和 React 开发任务,因此我需要从 Flask 后端提供文件以响应客户端,该客户端是从 Flask 后端的 GCP 云存储下载的。
所以我目前的方法如下。
@app.route('/api/download-file', methods=['GET'])
@token_required
def download_blob():
"""Downloads a blob."""
file_name = request.args.get('file_name')
storage_client = storage.Client()
bucket = storage_client.bucket(app.config.get('CLOUD_STORAGE_BUCKET'))
blob = bucket.blob(file_name)
print(blob.exists())
blob.download_to_filename(file_name)
return send_file("./" + file_name, as_attachment=True, mimetype="application/vnd.ms-excel")
所以我的问题是现在从烧瓶下载的所有文件都保存在服务器文件夹中,并且在返回语句之后,我无法执行删除该文件的行。
如果不保存在服务器内部,我找不到返回文件的任何解决方案
解决方案
基于 JohnHanley 的评论,可以使用以下代码实现目标。从这种方式可以提供任何文件而不用担心内容类型
@app.route('/api/download-file', methods=['GET'])
@token_required
def download_blob():
"""Downloads a blob."""
file_name = "dir/" + request.args.get('file_name')
storage_client = storage.Client()
bucket = storage_client.bucket(app.config.get('CLOUD_STORAGE_BUCKET'))
blob = bucket.get_blob(file_name)
content_type = None
try:
content_type = blob.content_type
except:
pass
file = blob.download_as_string()
print(type(file), "downloaded type")
return Response(file, mimetype=content_type)
推荐阅读
- c# - 组合 Lambda 表达式时出错:“从范围 '' 引用的 'Foo' 类型的变量 'foo',但未定义
- javascript - 如何根据另一个表单值显示表单域
- php - 数据表编辑,使用选择行功能删除顶部的常用按钮,而不使用编辑器数据表
- scala - DataFrame : 在 groupBy 上应用自定义函数
- c# - 非英文字符的 DateTimeOffset.TryParseExact()
- unit-testing - wrapper.find() 在单元测试中抛出错误
- python - 这个 python 脚本有什么问题?
- tensorflow - 支持 Nvidia CUDA Toolkit 9.2
- python - 使用 tf.estimator.Estimator 进行 TensorFlow 预测太慢
- php - Firebase 云消息传递 - PHP Rest API 不适用于 iOS