如何用Python标准库优雅打印Requests库的HTTP响应头?
仅用Python标准库优雅打印Requests响应头的方案
问题背景
需要以Pythonic方式、仅依赖标准库优雅打印Requests库返回的HTTP响应头,尝试JSON相关方法和第三方库rich时遇到错误,现寻求纯标准库实现方案。
已尝试的方法及问题
方法1:错误使用json.loads处理响应头
代码:
import json response_json = json.loads(response.headers) pretty_response = json.dumps(response_json, indent=4) print(pretty_response)
错误信息:
TypeError Traceback (most recent call last) Cell In[21], line 2 1 import json ----> 2 response_json = json.loads(response.headers) 4 pretty_response = json.dumps(response_json, indent=4) 5 print(pretty_response) File c:\ProgramData\Anaconda3\envs\webscrapers\lib\json\__init__.py:341, in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 339 else: 340 if not isinstance(s, (bytes, bytearray)): --> 341 raise TypeError(f'the JSON object must be str, bytes or bytearray, ' 342 f'not {s.__class__.__name__}') 343 s = s.decode(detect_encoding(s), 'surrogatepass') 345 if "encoding" in kw: TypeError: the JSON object must be str, bytes or bytearray, not CaseInsensitiveDict
问题:response.headers是Requests的CaseInsensitiveDict对象,并非JSON字符串,json.loads仅能处理字符串/字节类型,因此触发报错。
方法2:使用rich.print_json的错误用法
代码:
import json import rich rich.print_json(dict(response.headers))
错误信息:
TypeError: json must be str. Did you mean print_json(data={'Date': 'Sun, 18 Jun 2023 16:22:08 GMT', ...}
问题:rich.print_json默认接受JSON字符串,传入字典需指定data参数,但rich属于第三方库,不符合仅用标准库的要求。
纯标准库解决方案
方案1:使用json.dumps直接格式化字典
response.headers是字典子类,转为普通字典后直接用json.dumps的缩进参数格式化:
import json import requests response = requests.get("https://example.com") # 将CaseInsensitiveDict转为普通字典后格式化打印 print(json.dumps(dict(response.headers), indent=4))
输出示例:
{ "Accept-Ranges": "bytes", "Age": "12345", "Cache-Control": "max-age=604800", "Content-Type": "text/html; charset=UTF-8", "Date": "Sun, 18 Jun 2023 16:22:08 GMT", "Etag": "\"3147526947+ident\"", "Expires": "Sun, 25 Jun 2023 16:22:08 GMT", "Last-Modified": "Thu, 17 Oct 2019 07:18:26 GMT", "Server": "ECS (oxr/832E)", "Vary": "Accept-Encoding", "X-Cache": "HIT", "Content-Length": "1256" }
方案2:使用标准库pprint模块(更Pythonic)
pprint是Python标准库专门用于优雅打印数据结构的模块,支持字典的格式化输出:
import pprint import requests response = requests.get("https://example.com") # 直接打印转换后的字典,pprint自动处理缩进 pprint.pprint(dict(response.headers), indent=4)
输出示例:
{ 'Accept-Ranges': 'bytes', 'Age': '12345', 'Cache-Control': 'max-age=604800', 'Content-Length': '1256', 'Content-Type': 'text/html; charset=UTF-8', 'Date': 'Sun, 18 Jun 2023 16:22:08 GMT', 'Etag': '"3147526947+ident"', 'Expires': 'Sun, 25 Jun 2023 16:22:08 GMT', 'Last-Modified': 'Thu, 17 Oct 2019 07:18:26 GMT', 'Server': 'ECS (oxr/832E)', 'Vary': 'Accept-Encoding', 'X-Cache': 'HIT'}
方案3:手动格式化键值对(自定义排版)
如果需要更个性化的格式,比如键值对齐,可以手动遍历字典并格式化:
import requests response = requests.get("https://example.com") headers_dict = dict(response.headers) # 获取最长的键长度,用于对齐 max_key_len = max(len(key) for key in headers_dict.keys()) # 遍历打印每个键值对 for key, value in headers_dict.items(): print(f"{key.ljust(max_key_len)} : {value}")
输出示例:
Accept-Ranges : bytes Age : 12345 Cache-Control : max-age=604800 Content-Length : 1256 Content-Type : text/html; charset=UTF-8 Date : Sun, 18 Jun 2023 16:22:08 GMT Etag : "3147526947+ident" Expires : Sun, 25 Jun 2023 16:22:08 GMT Last-Modified : Thu, 17 Oct 2019 07:18:26 GMT Server : ECS (oxr/832E) Vary : Accept-Encoding X-Cache : HIT
内容的提问来源于stack exchange,提问作者Rich Lysakowski PhD
相关产品推荐
相关产品推荐

