简体   繁体   中英

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:

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. the try-exception Expression is from here

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.

>>> 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?

You have to pass the function as success argument. 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' . The actual error is raised on trying to call success() which translates to 'Sydney'() - something like str object is not callable

Proper call would be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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