当状态为类似400的错误并引发异常时,如何读取Python urllib上的响应正文?

Cir*_*四事件 5 python urllib

我正在尝试使用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
Run Code Online (Sandbox Code Playgroud)

GitHub很好,并解释了为什么它在响应正文上失败,如下所示:400 vs 422对数据POST的响应

那么,我如何阅读回复正文?有没有办法防止引发异常?

我尝试捕获异常并在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']
Run Code Online (Sandbox Code Playgroud)

用法:有人可以举一个在github中上传发布资产的python请求示例吗?

Wil*_*ing 8

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)
Run Code Online (Sandbox Code Playgroud)

该文档更详细地说明了该HTTPError实例如何用作响应及其一些其他属性。