代码之家  ›  专栏  ›  技术社区  ›  Derek 朕會功夫

回答只为具有正确内容类型的文件编写?

  •  3
  • Derek 朕會功夫  · 技术社区  · 7 年前

    response.write ? 这就是我一直在使用的:

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

    但这会将内容类型设置为 text/html .或是 响应.write 这不是正确的方法吗?

    2 回复  |  直到 7 年前
        1
  •  3
  •   Brendan Goggin    7 年前

    an example using mimetypes Webob Request/Response objects 模拟类型 可以找到 here . 模拟类型 是一个内置的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 而不是 模拟类型 this SO answer .

        2
  •  1
  •   GAEfan    7 年前

    尝试将内容类型添加到标题:

    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)