【问题标题】:Get variable outside exception Python获取异常Python之外的变量
【发布时间】:2016-03-09 15:42:31
【问题描述】:

我正在使用 urllib 调用 API。当某些事情与预期不符时,API 会向用户抛出错误(例如 HTTP Error 415: Unsupported Media Type)。但除此之外,API 返回一个包含更多信息的 JSON。我想将该 json 传递给异常并在那里解析它,这样我就可以向用户提供有关错误的信息。

这可能吗?如果,它是如何完成的?

额外信息:

错误:HTTPError

--编辑--

根据要求,这里有一些代码(我想在异常中读取响应):

def _sendpost(url, data=None, filetype=None):
    try:
        global _auth
        req = urllib.request.Request(url, data)
        req.add_header('User-Agent', _useragent)
        req.add_header('Authorization', 'Bearer ' + _auth['access_token'])
        if filetype is not None:
            req.add_header('Content-Type', filetype)
        resp = urllib.request.urlopen(req, data)
        data = json.loads(resp.read().decode('utf-8'), object_pairs_hook=OrderedDict)
    except urllib.error.HTTPError as e:
        print(e)
    return data

--编辑 2-- 我不想使用额外的库/模块。因为我不控制目标机器。

【问题讨论】:

  • 你能提供一些你一直在玩的代码吗?
  • @Jan 将代码添加到主要问题

标签: python json python-3.x


【解决方案1】:

代码

import urllib.request
import urllib.error

try:
    request = urllib.request.urlopen('https://api.gutefrage.net')
    response = urllib.urlopen(request)
except urllib.error.HTTPError as e:
    error_message = e.read()
    print(error_message)

输出

b'{"error":{"message":"X-Api-Key header is missing or invalid","type":"API_REQUEST_FORBIDDEN"}}'

未询问,但使用模块 json 您可以将其转换为 dict via

import json
json.loads(error_message.decode("utf-8"))

从字节串中得到字典。

【讨论】:

    【解决方案2】:

    如果您无法使用 urllib,那么您可以使用错误来读取响应的文本,并将其加载到 JSON 中。

    from urllib import request, error
    import json
    
    try:
        req = urllib.request.Request(url, data)
        req.add_header('User-Agent', _useragent)
        req.add_header('Authorization', 'Bearer ' + _auth['access_token'])
        if filetype is not None:
            req.add_header('Content-Type', filetype)
        resp = urllib.request.urlopen(req, data)
        data = json.loads(resp.read().decode('utf-8'), object_pairs_hook=OrderedDict)
    except error.HTTPError as e:
        json_response = json.loads(e.read().decode('utf-8'))
    

    如果您不拘泥于 urllib,我强烈建议您使用 requests 模块而不是 urllib。有了它,你可以有这样的东西:

    response = requests.get("http://www.example.com/api/action")
    if response.status_code == 415:
        response_json = response.json()
    

    requests在遇到非2xx系列响应码时不会抛出异常;相反,它无论如何都会返回响应并添加状态代码。

    您还可以为这些请求添加标头和参数:

    headers = {
        'User-Agent': _useragent,
        'Authorization': 'Bearer ' + _auth['access_token']
    }
    response = requests.get("http://www.example.com/api/action", headers=headers)
    

    【讨论】:

    • 我应该提到,它是一个模块供客户使用,我们希望尽可能少的外部模块。
    • @FalingDutchman 在安装过程中可以自动安装许多模块。在这种情况下,只有一个命令来安装它。
    • @ArtOfCode json.loads(e.read()) 不起作用,因为您必须先使用 decode 将其转换为字符串
    猜你喜欢
    • 2017-09-30
    • 1970-01-01
    • 2020-02-18
    • 2018-07-23
    • 2015-04-20
    • 1970-01-01
    • 2016-05-05
    • 1970-01-01
    • 2013-01-19
    相关资源
    最近更新 更多