Python

April 08, 2008

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.



Technorati Tags:
,


The Story of Stuff

Photoblog

Photography Site

Recent Images

  • www.flickr.com
    This is a Flickr badge showing public photos from jeremey. Make your own badge here.

Flickr

  • jeremey. Get yours at bighugelabs.com/flickr

Houston Photobloggers

Blog powered by TypePad