Python:try-except表达式在我尝试将其应用于http请求时总是获取默认值
我使用一些谷歌API作为参考:Python:try-except表达式在我尝试将其应用于http请求时总是获取默认值,python,http,exception,xmlhttprequest,Python,Http,Exception,Xmlhttprequest,我使用一些谷歌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:
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异常时,如果网络出现错误,请处理exoption。
但是当我尝试使用这些异常时,我总是会得到http的失败结果,即使我只运行success函数就得到了成功的结果
>>> re=get_address(-33.865, 151.2094)
>>> re
'Sydney'
>>> r=try_except(get_address(-33.865, 151.2094),"")
>>> r
''
如何确保成功的结果得到正确的字符串reuslt,而http请求的唯一失败得到失败的结果?您必须将函数作为
success
参数传递。目前在
r=try_except(get_address(-33.865, 151.2094),"")
您正在传递get_address(-33.865151.2094)
的结果值,即'Sydney'
。在尝试调用success()
时会出现实际错误,这将转换为'Sydney'()
-类似str的对象是不可调用的
合适的电话是
r=try_except(lambda: get_address(-33.865, 151.2094), '')
这就是为什么您应该始终捕获预期的特定异常。您正在捕获所有的
异常
s,隐藏非常有用的异常消息,该消息会准确地告诉您发生了什么。
r=try_except(lambda: get_address(-33.865, 151.2094), '')