Python:try-except 表达式在我尝试在 http 请求上应用它时总是获得默认值



我使用一些谷歌API作为研究员:

def get_address(lat, lng):
    url = "https://maps.googleapis.com/maps/api/geocode/json?{}".
      format(urllib.parse.urlencode(args))
    ...
    try:
       r = requests.get(url)
       ...
       return r
    except OSError as e:
       raise NetException(e.message, 400)

当我尝试使用try-exception处理如果网络错误时。try-exception 表达式来自这里

def try_except(success, failure, *exceptions):
    try:
        return success()
    except exceptions or Exception:
        return failure() if callable(failure) else failure

但是当我尝试使用这些异常时,我总是得到 http 的失败结果,即使如果我只是运行成功函数,我也会得到成功的结果。

>>> re=get_address(-33.865, 151.2094)
>>> re
'Sydney'
>>> r=try_except(get_address(-33.865, 151.2094),"")
>>> r
''

如何确保成功的结果会得到正确的字符串重用,而http请求的onlly失败会得到失败的结果?

您必须将函数作为success参数传递。目前在

r=try_except(get_address(-33.865, 151.2094),"")

您传递的结果值为 get_address(-33.865, 151.2094) 'Sydney' 。尝试调用转换为'Sydney'()success()时会引发实际错误 - 类似于str object is not callable

正确的调用将是

r=try_except(lambda: get_address(-33.865, 151.2094), '')

最新更新