write argument must be string
So I was writing a web application using WSGI and - after working for a long time - it started erroring out with:
AssertionError: write() argument must be string
from deep inside the WSGI handler. Now, this usually means that you're returning unicode, which WSGI can't handle. However, it's quite happy to return a bytestream, so you can fix this by encoding your return from the application function:
x = "<html><body><p>dfgdfgfdg</p></body></html>".encode('utf-8') response_headers = [ ('Content-Type', 'text/html; charset=UTF-8'), ('Content-Length', str (len (x))), ] start_response ('200 OK', response_headers) return [x]
Note how the return text is always sent as an item of a list. This is because WSGI insists that you return an iterable, and if you send back a naked string, it will iterate over each character.
But still, I had an error. It was only when I tried to print out the response text that I realised what was going on. I never got to the print out point. In fact, I never got to the return from the application function - because I was accidentally returning from earlier in the function. Despite that return had no headers, WSGI errored out on its type: unicode text. So, easily fixed.