Parse an HTTP request Authorization header with Python
Posted
by Kris Walker
on Stack Overflow
See other posts from Stack Overflow
or by Kris Walker
Published on 2009-08-28T21:07:56Z
Indexed on
2010/05/14
0:24 UTC
Read the original article
Hit count: 643
I need to take a header like this:
Authorization: Digest qop="chap",
realm="[email protected]",
username="Foobear",
response="6629fae49393a05397450978507c4ef1",
cnonce="5ccc069c403ebaf9f0171e9517f40e41"
And parse it into this using Python:
{'protocol':'Digest',
'qop':'chap',
'realm':'[email protected]',
'username':'Foobear',
'response':'6629fae49393a05397450978507c4ef1',
'cnonce':'5ccc069c403ebaf9f0171e9517f40e41'}
Is there a library to do this, or something I could look at for inspiration?
I'm doing this on Google App Engine, and I'm not sure if the Pyparsing library is available, but maybe I could include it with my app if it is the best solution.
Currently I'm creating my own MyHeaderParser object and using it with reduce() on the header string. It's working, but very fragile.
Brilliant solution by nadia below:
import re
reg = re.compile('(\w+)[=] ?"?(\w+)"?')
s = """Digest
realm="stackoverflow.com", username="kixx"
"""
print str(dict(reg.findall(s)))
© Stack Overflow or respective owner