Python中漂亮打印requests.response标头的简单方法。

huangapple go评论64阅读模式
英文:

SIMPLE Pythonic way to Pretty Print requests.response Headers

问题

我正在尝试以完全符合Python标准库的方式漂亮地打印从Python Requests库返回的HTTP响应,而不使用任何不在Python标准库中的包。我遇到了JSON处理的问题。

我尝试过的方法:

我尝试使用json.loads()将响应头加载到JSON字符串中,然后使用json.dumps()进行缩进输出,如下所示:

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)
...
TypeError: the JSON object must be str, bytes or bytearray, not CaseInsensitiveDict

我还尝试过:

首先安装和导入rich包,然后使用rich包中的一个模块来实现富文本格式化输出到终端。print_json()函数应该漂亮地打印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包并参考如何漂亮地打印嵌套字典?Requests:漂亮地打印HTTP响应头中的一些提示,成功解决了问题:

import rich
rich.pretty.pprint(dict(response.headers))

然而,要找出正确的语法花了一些时间,因为Jupyter中的rich.pretty.pprinthelp()文档没有针对这种用例提供详细的示例。虽然rich是一个非常好的包,但它有一个显著的学习曲线。更重要的是,它不是Python的内置解决方案。

如何在不安装第三方包的情况下简单地使用Python完成这个任务?

英文:

I am trying to pretty print the http response coming back from Python Requests library in a fully Pythonic way without using any packages not built into the Python Standard Library. I am getting the JSON run around.

What I tried:

I tried loading the response.headers into a JSON string using json.loads(), and then indenting the output using json.dumps(), as follows,

import json
response_json = json.loads(response.headers)

pretty_response = json.dumps(response_json, indent=4)
print(pretty_response)

but I get the following error:

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

I also tried:

First installing and importing the rich package, and then using a module within the rich package for Rich Text Formatting output to terminals. The print_json() function is supposed to pretty print json:

import json
import rich
rich.print_json(dict(response.headers))

but I get an error:

TypeError: json must be str. Did you mean print_json(data={'Date': 'Sun, 18 Jun 2023 16:22:08 GMT', ...}

I finally got it to work by installing and importing the rich package and using some hints from How to pretty print nested dictionaries? and Requests: Pretty print http response headers.

import rich
rich.pretty.pprint(dict(response.headers))

However, it took some time to figure out the correct syntax, because the rich.pretty.pprint help() documentation in Jupyter did not have detailed examples for this use case. While rich is a very nice package, it has a significant learning curve. More importantly, it is not a native Python built-in solution.

How can this be done simply using Python with no 3rd party package installations?

答案1

得分: 2

from pprint import pprint

pprint(dict(response.headers))
英文:
from pprint import pprint

pprint(dict(response.headers))

huangapple
  • 本文由 发表于 2023年6月19日 01:03:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76501677.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定