【问题标题】:webapp2 and mod_wsgi serving Content-Type: image/jpegwebapp2 和 mod_wsgi 服务 Content-Type: image/jpeg
【发布时间】: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


【解决方案1】:

@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...

【讨论】:

  • mod_wsgi 严格遵守 WSGI 规范。其他 WSGI 服务器,尤其是纯 Python 实现相当草率,并且可以允许一些实际上违反 WSGI 规范的事情。当您想要编写实际上可跨 WSGI 服务器实现移植的代码时,这种纯 Python WSGI 服务器可能会很痛苦。
猜你喜欢
  • 2021-11-08
  • 2014-03-14
  • 2020-09-22
  • 1970-01-01
  • 1970-01-01
  • 2019-03-06
  • 2022-06-30
  • 2017-03-16
  • 1970-01-01
相关资源
最近更新 更多