How to read the response body on Python urllib when the status is an error like 400 which raises an exception?

后端 未结 1 1504
暗喜
暗喜 2021-01-02 04:41

I\'m trying to make a request to the GitHub API with Python 3 urllib to create a release, but I made some mistake and it fails with an exception:



        
相关标签:
1条回答
  • 2021-01-02 05:01

    The HTTPError has a read() method that allows you to read the response body. So in your case, you should be able to do something such as:

    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 explain in more detail how the HTTPError instance can be used as a response, and some of its other attributes.

    0 讨论(0)
提交回复
热议问题