Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python webapp2和mod_wsgi服务内容类型:image/jpeg_Python_Python 2.7_Mod Wsgi_Content Type_Webapp2 - Fatal编程技术网

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

Python webapp2和mod_wsgi服务内容类型:image/jpeg,python,python-2.7,mod-wsgi,content-type,webapp2,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 = ...

我有一个
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()
一切都很顺利;当我转到url时,我看到一个图像。但我添加了以下内容以通过mod_wsgi运行它:

def application(environ, start_response):
    resp = app.get_response(environ['PATH_INFO'])
    start_response(resp.status, resp.headerlist)
    yield resp.body
我得到一个
500内部服务器错误
,日志中有以下内容:

[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'>
>>img.\uu类__
>>>导入webapp2
>>>app=webapp2.WSGIApplication([('/false',webapp2.RequestHandler)])
>>>resp=app.get_响应('/fake')
>>>分别写入(img)
>>>相应的主体__

所有这些都适用于一个单独的
RequestHandler
,具有
内容类型:text/html
和一个简单的文本响应。这里发生了什么事?如何强制使用字节字符串(在python 2.7.4中)?

@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')]

内容类型
是unicode…

错误是报头值,而不是正文。你能尝试登录/转储/吗<在您的WSGI应用程序中,代码>响应标题列表?mod_WSGI严格遵守WSGI规范。其他WSGI服务器,特别是纯Python实现非常松散,可能会允许一些实际上违反WSGI规范的事情。当您想要编写可跨WSGI服务器实现移植的代码时,这种纯Python WSGI服务器可能会让您感到痛苦。