Parse an HTTP request Authorization header with Python
- by Kris Walker
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)))