Python Tips: Parse HTTP in One Line
I love asyncore and asynchat. They do protocol engine grunt work for you. But they won't parse your protocol beyond finding the end of a message, so here's a quick tip for parsing an array of disorganized buffers into a dictionary of headers (for HTTP/SIP-style protocols). Remember that the first line is the command, not a header.
lines = "".join(buffers).split("\r\n")
command = lines[0]
headers = dict(map(lambda x: x.split(': ', 1), lines[1:]))
Thar ya go. So it's not one line... it could be, but it would be much uglier because the first line of the protocol is unique.




Recent Comments