QPID Python API – Careful with your content…

Just wanted to throw out something that to me wasn’t obvious.

We ran into an issue today where  our send was crashing.  Nothing crazy about the code something like

message = Message()
message.subject = "headache"
message.content = message_content
sender.send(message)

And then we crashed… :

UnicodeDecodeError: ‘utf8’ codec can’t decode byte 0xb6 in position 31: invalid start byte

What most people would ask would be.. well what is your content?  It was a string, but it was a unicode string and the api handles those differently.  So set message_content to:

message_content=u'Et tu brute?'

And your test will crash.  Basically this issue generally isn’t experienced because people use the content and subject arguments of the Message() constructor

message = Message(content=u'Et tu brute?')

When you do this, it will "infer" the content_type from the content provided.  It just happens that for regular strings it will set the content_type to None.  If we would have passed our content to the constructor it would have set the content_type to "text/plain" because the content is a unicode string.

So in our example above we needed to do:

message = Message()
message.subject = "headache"
message.content = message_content
message.content_type="text/plain"
#or we could do getType(message.content) its inside of the messaging module
sender.send(message)
#no crash.

To me this is an annoyance, esp when dealing with strings in python…  just wanted to throw it out there before someone else experiences the same issue I have.

A final note is when printing messages

message = Message()
message.subject = "headache"
message.content = message_content
print message
message.content_type="text/plain"
print message

Prints out something like:

>  Message(subject=’headache’, content_type=None, content=u’secret content’)

>  Message(subject=’headache’, content=u’secret content’)

Notice that there is a "content_type" property in the first, and not the second… why you might ask?  Well it only prints out the content_type IF your content_type DOESN’T match your content….  I did not know this until after this horrific finding but now that I know, this is a huge red flag, that something is wrong with your message.

Tagged with: ,
Posted in Python, Qpid

Leave a comment