Domanda

I have a webapp2.RequestHandler that gets images like so:

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()

It all works hunky dory; I go to the url, I see an image. But I added the following to run it thru mod_wsgi:

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

And I get a 500 Internal Server Error with the following in the logs:

[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

If I load up the img the same way in the interpreter, it is not a unicode string:

>>> 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'>

All the above works for a separate RequestHandler with Content-Type: text/html and a simple text response. What's happening here? How can I force a byte string (in python 2.7.4)?

È stato utile?

Soluzione

@sk1p, the wonderful commenter above, pointed out my issue is not with the response body, but with one of the headers:

>>> 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 was unicode...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top