response.write 但对于内容类型正确的文件?

response.write but for files with correct content-type?

有没有办法 return 具有正确内容类型的文件(例如图像、脚本)response.write?这是我一直在使用的:

with open(path) as f:
    self.response.write(f.read())

但这会将内容类型设置为 text/html。还是 response.write 不是解决这个问题的正确方法?

尝试将内容类型添加到 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)

我找到了 an example using mimetypes in the Webob documentation (webapp2 requests and responses are Webob Request/Response objects). Documentation on mimetypes can be found heremimetypes 是内置的 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 instead of mimetypes would work as well and might be worth looking into, as @Dan Cornilescu pointed out. He linked to this SO answer.