gpt4 book ai didi

python - 如何在 python 中测试对 post 请求的 401 响应?

转载 作者:行者123 更新时间:2023-11-30 22:58:47 25 4
gpt4 key购买 nike

我正在使用发布请求来访问需要身份验证的网站。如果身份验证不正确,我会收到响应 [401]。我想测试身份验证是否不正确,如果是,则中止该过程并显示某种错误。我不知道测试响应是否为 401 的语法。

output = requests.post(cfg.get('HTTP', 'url'), data = query, verify=False, auth=HTTPBasicAuth(credentials['user'], credentials['pass']))

if output == '<Response [401]>':
sys.exit('Incorrect Authentication. Please try again.')
else:
sys.exit('manual stop1')

而不是 '<Response [401]>' ,我也尝试过'Response [401]' , 'response [401]' , '<Response[401]>' , 'Response[401]' , 'response[401]' , '[401]' , '401' ,以及所有不带引号的内容。

我已经看到一些使用flask和json的响应,但我希望不必改变我请求数据的方式。谢谢!

最佳答案

您需要 status_code 属性

if output.status_code == 401:
...

或者避免对数字进行硬编码:

if output.status_code == requests.status_codes.codes.UNAUTHORIZED:
....

关于python - 如何在 python 中测试对 post 请求的 401 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36048692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com