有没有办法用response.write
返回正确内容类型的文件(例如图像,脚本)?这是我一直使用的是什么:response.write但文件的内容类型是否正确?
with open(path) as f:
self.response.write(f.read())
但这将内容类型text/html
。或者是response.write
不正确的方法来解决这个问题?
有没有办法用response.write
返回正确内容类型的文件(例如图像,脚本)?这是我一直使用的是什么:response.write但文件的内容类型是否正确?
with open(path) as f:
self.response.write(f.read())
但这将内容类型text/html
。或者是response.write
不正确的方法来解决这个问题?
我发现an example using mimetypes
所述的WebOb文档中(webapp2的请求和响应是Webob Request/Response objects)。关于mimetypes
的文档可以在here找到。 mimetypes
是一个内置的python模块将文件扩展名映射到MIME类型。
我发现的例子包括这样的功能:
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'
您可以使用该功能在您的处理程序,如下所示:
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())
注意:在使用python-magic
代替mimetypes
会工作,以及与可能值得关注的是,正如@ Corn Cornilescu指出的那样。他链接到this SO answer。
尝试添加内容类型报头:
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)
问题是代码可能不知道内容类型可能是什么。 –
这*可能*帮助:https://stackoverflow.com/questions/10937350/how-to-check-type-of-files-without-extensions-in-python –
编辑答案。但是,正如Dan所说,Python Magic应该做到这一点。 – GAEfan
真棒,完美的作品。 –