简体   繁体   English

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

[英]Python: try-except Expression always get the default value when I try to apply it on http request

I use some google API as fellow:我使用一些谷歌 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)

while I try use the try-exception handle the excption if the network errors.而我尝试使用 try-exception 处理网络错误时的异常。 the try-exception Expression is from here try-exception 表达式来自这里

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

But when I try to use these exception I always get the failure reults of http, even if I get successful result if I simply run the success function.但是当我尝试使用这些异常时,我总是得到 http 的失败结果,即使我只是运行成功函数也能得到成功的结果。

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

How to make sure the successful result would get correct string reuslt, while the onlly failture of http request get the failure result?如何确保成功的结果会得到正确的字符串reuslt,而http请求的唯一失败会得到失败的结果?

You have to pass the function as success argument.您必须将该函数作为success参数传递。 Currently in目前在

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

you are passing result value of get_address(-33.865, 151.2094) which is 'Sydney' .您正在传递get_address(-33.865, 151.2094)结果值,即'Sydney' The actual error is raised on trying to call success() which translates to 'Sydney'() - something like str object is not callable实际错误是在尝试调用success()引发的,它转换为'Sydney'() - 像str object is not callable这样的东西str object is not callable

Proper call would be正确的调用是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM