Saturday, September 28, 2013

[Python] TypeError: str does not support buffer interface

When writing data, such as to sockets, you probably see a lot of code that calls a write function and passes in a string like this:
self.wfile.write('Hello World')


This code ran perfectly well in Python 2.x, but not so in Python 3.x. In Python 2.x, strings that contained only ASCII characters could be passed as data but if the strings contained characters that couldn't be represented as ASCII characters, a UnicodeDecodeError would occur.

Python 3.x treats text and binary data as distinct types, and raises a TypeError if you provided text where binary data was expected. In Python 3.x, you have to convert text data to binary data using the bytes function, so expect to rewrite your code to look like the following:
self.wfile.write(bytes('Hello World', 'UTF-8'))

No comments: