在使用requests的过程中,无意间发现,返回的响应信息中,headers存储在一个对大小写不敏感的字典中
import requests
url = 'http://www.baidu.com'
res = requests.get(url)
print(res.headers['Connection'])
print(res.headers['connection'])
程序输出结果
keep-alive
keep-alive
出于探索技术的兴趣,我想自己实现一个类似的字典,字典对key的大小写不敏感,这个类应当以dict为父类,并重载几个方法:
class IgnoreCaseDict(dict):
def lower_key(self, key):
if isinstance(key, str):
return key.lower()
return key
def __setitem__(self, key, value):
super().__setitem__(self.lower_key(key), value)
def __getitem__(self, item):
return super().__getitem__(self.lower_key(item))
def __delitem__(self, key):
super().__delitem__(self.lower_key(key))
def update(self, another=None, **F):
for key, value in another.items():
self.__setitem__(key, value)
def __repr__(self):
return f"{type(self).__name__}({super().__repr__()})"
icd = IgnoreCaseDict()
icd['language'] = 'python'
print(icd)
icd['Language'] = 'PYTHON'
print(icd)
icd_2 = IgnoreCaseDict()
icd_2['Type'] = '类型'
icd.update(icd_2)
print(icd)
print(icd['TYPE'])
程序输出结果
IgnoreCaseDict({'language': 'python'})
IgnoreCaseDict({'language': 'PYTHON'})
IgnoreCaseDict({'language': 'PYTHON', 'type': '类型'})
类型
QQ交流群: 211426309