[英]response.write but for files with correct content-type?
Is there a way to return a file (ex. images, scripts) with correct content type with response.write
? 有没有一种方法可以使用
response.write
返回具有正确内容类型的文件(例如图像,脚本)? This is what I have been using: 这就是我一直在使用的:
with open(path) as f:
self.response.write(f.read())
but this sets the content type as text/html
. 但这会将内容类型设置为
text/html
。 Or is response.write
not the correct way to approach this? 还是
response.write
不是解决此问题的正确方法?
I found an example using mimetypes
in the Webob documentation (webapp2 requests and responses are Webob Request/Response objects ). 我在Webob文档中找到了一个使用
mimetypes
的示例 (webapp2请求和响应是Webob Request / Response对象 )。 Documentation on mimetypes
can be found here . 有关
mimetypes
文档可以在这里找到。 mimetypes
is a built-in python module mapping file extensions to MIME type. mimetypes
是将文件扩展名映射到MIME类型的内置python模块。
The example I found includes this function: 我发现的示例包含此功能:
import mimetypes
def get_mimetype(filename):
type, encoding = mimetypes.guess_type(filename)
# We'll ignore encoding, even though we shouldn't really
return type or 'application/octet-stream'
You can use that function in your handler like so: 您可以在处理程序中使用该函数,如下所示:
def FileHandler(webapp2.RequestHandler):
# I'm going to assume `path` is a route arg
def get(self, path):
# set content_type
self.response.content_type = get_mimetype(path)
with open(path) as f:
self.response.write(f.read())
Note: using python-magic
instead of mimetypes
would work as well and might be worth looking into, as @Dan Cornilescu pointed out. 注意:使用
python-magic
代替mimetypes
也可以,并且@@ Dan Cornilescu指出,可能值得研究。 He linked to this SO answer . 他链接到此答案 。
Try adding the content type to the header: 尝试将内容类型添加到标题中:
my_file = f.read()
content_type = my_file.headers.get('Content-Type', 'text/html')
self.response.headers.add_header("Content-Type",content_type)
self.response.write(my_file)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.