【发布时间】:2014-01-08 12:37:27
【问题描述】:
我有一个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'>
以上所有内容都适用于带有Content-Type: text/html 的单独RequestHandler 和简单的文本响应。这里发生了什么事?如何强制一个字节字符串(在 python 2.7.4 中)?
【问题讨论】:
-
该错误是抱怨标题值,而不是正文。您可以尝试在您的 WSGI 应用程序中记录/转储/...
resp.headerlist吗?
标签: python python-2.7 mod-wsgi content-type webapp2