Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 Python urllib3错误处理_Python 2.7 - Fatal编程技术网

Python 2.7 Python urllib3错误处理

Python 2.7 Python urllib3错误处理,python-2.7,Python 2.7,我对Python相当陌生,希望获得一些关于如何在Python 2.7上使用urrlib3处理身份验证错误的指导。我当前的用例是使用SNAPI自动创建ServiceNow票证。为了做到这一点,我有下面的代码片段来使用我的用户名/密码并获得一个令牌来登录 r = session.post(auth_url, json=login_data, verify=False) web_token = r.text 这是工作正常,但我想一个更干净的方式通知自己,如果有一个错误的代码。如果用户名/密码不正确,

我对Python相当陌生,希望获得一些关于如何在Python 2.7上使用urrlib3处理身份验证错误的指导。我当前的用例是使用SNAPI自动创建ServiceNow票证。为了做到这一点,我有下面的代码片段来使用我的用户名/密码并获得一个令牌来登录

r = session.post(auth_url, json=login_data, verify=False)
web_token = r.text
这是工作正常,但我想一个更干净的方式通知自己,如果有一个错误的代码。如果用户名/密码不正确,我将从SN web服务器获取此信息

{
  "error": "Authentication failure"
}
最初我打算使用try/exception,但在这种情况下,它似乎不会很好地工作,因为代码工作正常,这不是我所期望的输入。所以我的第二个想法是按照以下思路做一些事情:

if r.text does not contain "error"
then continue on my doe
else send an email telling me the error code
在编写代码之前,我想看看这是否是处理此类错误的最佳方法,或者我是否应该走另一条路

谢谢,
Eric

我和一位朋友谈过,他推荐了以下方法,该方法似乎效果很好,比使用if/match语句更简洁

try:
    r = session.post(auth_url, json=login_data, verify=False)
    web_token = r.text
    r.raise_for_status()
except Exception as e:
    print(e)