webapp2和mod_wsgi服务内容类型:image / jpeg

时间:2013-12-19 19:37:40

标签: python python-2.7 mod-wsgi content-type webapp2

我有一个webapp2.RequestHandler可以获得如下图像:

class ImageHandler(webapp2.RequestHandler):
    def get(self):
        # do some stuff to magically choose an image
        # i'm going to omit that because it's not relevant to the question
        img = ...
        self.response.content_type = 'image/jpeg'
        self.response.write(img)

app = webapp2.WSGIApplication([('/image', ImageHandler)], debug=True)

def main():
    from paste import httpserver
    httpserver.serve(app, host='127.0.0.1', port='8080')

if __name__ == '__main__':
    main()

这一切都很有效;我去了网址,我看到了一张图片。但我添加了以下内容以通过mod_wsgi运行它:

def application(environ, start_response):
    resp = app.get_response(environ['PATH_INFO'])
    start_response(resp.status, resp.headerlist)
    yield resp.body

我在日志中收到500 Internal Server Error以下内容:

[Thu Dec 19 14:25:57 2013] [error] [client 172.16.18.37] mod_wsgi (pid=32457): Exception occurred processing WSGI script '/data/www/wsgi/main.py'.
[Thu Dec 19 14:25:57 2013] [error] [client 172.16.18.37] TypeError: expected byte string object for header value, value of type unicode found

如果我在解释器中以相同的方式加载img,它不是unicode字符串:

>>> img.__class__
<type 'str'>
>>> import webapp2
>>> app = webapp2.WSGIApplication([('/fake', webapp2.RequestHandler)])
>>> resp = app.get_response('/fake')
>>> resp.write(img)
>>> resp.body.__class__
<type 'str'>

以上所有内容适用于单独的RequestHandler Content-Type: text/html和简单的文字回复。这里发生了什么事?如何强制一个字节串(在python 2.7.4中)?

1 个答案:

答案 0 :(得分:0)

@ sk1p,上面这位出色的评论者指出我的问题不在于回复正文,而在于其中一个标题:

>>> import main
>>> resp = main.app.get_response('/image')
>>> resp.headerlist
[('Content-Type', u'image/jpg; charset=utf-8'), ('Content-Length', '4369913'), ('Cache-Control', 'no-cache')]

Content-Type是unicode ......