【发布时间】:2016-10-02 16:05:22
【问题描述】:
我正在使用带有 python 2.7 的 Google App Engine。并且需要在内存中生成 xls 文件并发送给用户下载。
我在网上找到了大量的主题,但其中任何一个都帮不了我。 我尝试使用的相关主题:1)this is with Blobs, I tried at first,2)without Blob,3)with force-download MIME type,我也尝试使用 googlecloudstorage(找不到主题链接)。
这是我的代码:
import StringIO
class ExcelHandler(BaseHandler):
def post(self):
"""Save members to excel document and send to user"""
sheet = pyexcel.Sheet([[1, 2], [3, 4]])
filesheet = StringIO.StringIO()
sheet.save_to_memory('xls', filesheet)
filesheet.close()
self.response.write(sheet)
self.response.headers['Content-Type'] = 'application/force-download'
self.response.headers['Content-Transfer-Encoding'] = 'utf-8'
self.response.headers['Content-Disposition'] = 'attachment; filename=test.xlsx'
问题在于发送响应(而不是创建文件)。我尝试了不同的“内容类型”: '应用程序/vnd.ms-excel', '应用程序/下载', '应用程序/强制下载', '应用程序/八位字节流', 'application/vnd.openxmlformats - officedocument.spreadsheetml.sheet'
但我得到的最佳反应如图所示:
我无法强制我的浏览器开始从服务器下载数据。我想我的请求中可能有一些内容应该对服务器说“嘿,我想下载”,但这只是我的想法,我还没有找到任何相关信息。将不胜感激!
这也是我的要求:
POST /reg/excel HTTP/1.1
Host: 0.0.0.0:8080
Connection: keep-alive
Content-Length: 0
Accept: */*
Origin: http://0.0.0.0:8080
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36
Referer: http://0.0.0.0:8080/competition?dbKey=agpkZXZ- dG1tb3NjchgLEgtDb21wZXRpdGlvbhiAgICAgICgCww
Accept-Encoding: gzip, deflate
Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4
和调试器的响应:
HTTP/1.1 200 OK
content-disposition: attachment; filename=test.xlsx
content-transfer-encoding: utf-8
cache-control: no-cache
content-type: application/force-download
Content-Length: 64
Server: Development/2.0
Date: Sun, 02 Oct 2016 15:36:20 GMT
编辑 1:(尝试 voscausa 的回答)
【问题讨论】:
标签: python excel google-app-engine