如何使用python flask通过googleappengine提供pdf(或非图像)文件?

2024-03-29 15:55:50 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我当前用于上载所获取文件的代码:

header = file.headers['Content-Type']
parsed_header = parse_options_header(header)
blob_key = parsed_header[1]['blob-key']
UserObject(file = blobstore.BlobKey(blob_key)).put()

在发球端,我试着做同样的事情,我做的图像。也就是说,我得到了UserObject然后 photoUrl = images.get_serving_url(str(userObject.file))。在

令我惊讶的是,这种黑客攻击在本地服务器上运行得很好。但是,在生产过程中,它引发了一个例外:

^{pr2}$

存储/服务非图像文件(如pdf)的正确方法是什么?在


Tags: 文件key代码parsetypecontentparsedblob
1条回答
网友
1楼 · 发布于 2024-03-29 15:55:50

不要使用imagesAPI,因为它执行图像内容/格式检查,而您没有提供图像,因此它不会工作(至少在生产中)。在

您可以使用处理程序拥有自己的请求路径名称空间,就像应用程序中的任何其他处理程序一样,可能是这样:

def pdfServingUrl(request, blob_key):
    from urlparse import urlsplit, urlunsplit
    split = list(urlsplit(request.url))
    split[2] = '/PDF?key=%s' % blob_key.urlsafe() # rewrite the url 'path'
    return urlunsplit(tuple(split))

/PDF*的处理程序中:

^{pr2}$

如果您使用the Blobstore API on top of Google Cloud Storage,您也可以使用直接GCS访问路径,如这个答案所述:https://stackoverflow.com/a/34023661/4495081。在

注意:上面的代码是一个简单的python建议,仅用于访问blob数据。附加的东西,如头等等,没有被处理。在

根据@NicolaOtasevic的评论,flask更完整的代码可能如下所示:

blob_info = blobstore.get(request.args.get('key')) 
response = make_response(blob_info.open().read()) 
response.headers['Content-Type'] = blob_info.content_type 
response.headers['Content-Disposition'] = 'filename="%s"' % blob_info.filename

相关问题 更多 >