gpt4 book ai didi

python - 当状态为引发异常的 400 之类的错误时,如何读取 Python urllib 上的响应主体?

转载 作者:太空狗 更新时间:2023-10-30 02:15:09 24 4
gpt4 key购买 nike

我正在尝试使用 Python 3 urllib 向 GitHub API 发出请求以创建一个版本,但我犯了一些错误并且失败并出现异常:

Traceback (most recent call last):
File "./a.py", line 27, in <module>
'Authorization': 'token ' + token,
File "/usr/lib/python3.6/urllib/request.py", line 223, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python3.6/urllib/request.py", line 532, in open
response = meth(req, response)
File "/usr/lib/python3.6/urllib/request.py", line 642, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python3.6/urllib/request.py", line 570, in error
return self._call_chain(*args)
File "/usr/lib/python3.6/urllib/request.py", line 504, in _call_chain
result = func(*args)
File "/usr/lib/python3.6/urllib/request.py", line 650, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 422: Unprocessable Entity

不过,GitHub 很好,并解释了为什么它在响应正文中失败,如下所示:400 vs 422 response to POST of data

那么,我该如何读取响应正文呢?有没有办法防止引发异常?

我试图捕获异常并在 ipdb 中探索它,它给出了一个 urllib.error.HTTPError 类型的对象但我在那里找不到正文数据,只有标题。

脚本:

#!/usr/bin/env python3

import json
import os
import sys

from urllib.parse import urlencode
from urllib.request import Request, urlopen

repo = sys.argv[1]
tag = sys.argv[2]
upload_file = sys.argv[3]

token = os.environ['GITHUB_TOKEN']
url_template = 'https://{}.github.com/repos/' + repo + '/releases'

# Create.
_json = json.loads(urlopen(Request(
url_template.format('api'),
json.dumps({
'tag_namezxcvxzcv': tag,
'name': tag,
'prerelease': True,
}).encode(),
headers={
'Accept': 'application/vnd.github.v3+json',
'Authorization': 'token ' + token,
},
)).read().decode())
# This is not the tag, but rather some database integer identifier.
release_id = _json['id']

用法:Can someone give a python requests example of uploading a release asset in github?

最佳答案

HTTPError 有一个read() 方法,允许您读取响应主体。因此,在您的情况下,您应该能够执行以下操作:

try:
body = urlopen(Request(
url_template.format('api'),
json.dumps({
'tag_namezxcvxzcv': tag,
'name': tag,
'prerelease': True,
}).encode(),
headers={
'Accept': 'application/vnd.github.v3+json',
'Authorization': 'token ' + token,
},
)).read().decode()
except urllib.error.HTTPError as e:
body = e.read().decode() # Read the body of the error response

_json = json.loads(body)

The docs更详细地解释 HTTPError 实例如何用作响应,以及它的一些其他属性。

关于python - 当状态为引发异常的 400 之类的错误时,如何读取 Python urllib 上的响应主体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52364593/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com