用Python解析HTTP请求授权标头 [英] Parse an HTTP request Authorization header with Python

查看:214
本文介绍了用Python解析HTTP请求授权标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 授权:摘要qop =chap,
realm =testrealm@host.com,
username =Foobear,
response =6629fae49393a05397450978507c4ef1,
cnonce =5ccc069c403ebaf9f0171e9517f40e41

使用Python解析它:

  { 'protocol':'Digest',
'qop':'chap',
'realm':'testrealm@host.com',
'username':'Foobear',
'response':'6629fae49393a05397450978507c4ef1',
'cnonce':'5ccc069c403ebaf9f0171e9517f40e41'}

有没有图书馆可以做到这一点,或者我可以从中获得灵感?



我在Google App Engine上这样做,我不确定是否Pyparsing库是可用的,但也许我可以包括它与我的应用程序,如果它是最好的解决方案。



目前我创建我自己的MyHeaderParser目标ct并在头字符串中使用reduce()。这是工作,但非常脆弱。



下面是nadia的完美解决方案:

  import re 

reg = re.compile('(\w +)[=]??(\w +)?')

s = 摘要
realm =stackoverflow.com,username =kixx


print str(dict(reg.findall(s)))


解决方案

有一点正则表达式:

  import re 
reg = re.compile('(\w +)[:=]??(\w +)?')

>>> dict(reg.findall(headers))

{'username':'Foobear','realm':'testrealm','qop': 'chap','cnonce':'5ccc069c403ebaf9f0171e9517f40e41','response':'6629fae49393a05397450978507c4ef1','Authorization':'Digest'}


I need to take a header like this:

 Authorization: Digest qop="chap",
     realm="testrealm@host.com",
     username="Foobear",
     response="6629fae49393a05397450978507c4ef1",
     cnonce="5ccc069c403ebaf9f0171e9517f40e41"

And parse it into this using Python:

{'protocol':'Digest',
  'qop':'chap',
  'realm':'testrealm@host.com',
  '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)))

解决方案

A little regex:

import re
reg=re.compile('(\w+)[:=] ?"?(\w+)"?')

>>>dict(reg.findall(headers))

{'username': 'Foobear', 'realm': 'testrealm', 'qop': 'chap', 'cnonce': '5ccc069c403ebaf9f0171e9517f40e41', 'response': '6629fae49393a05397450978507c4ef1', 'Authorization': 'Digest'}

这篇关于用Python解析HTTP请求授权标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆