我的问题与this one密切相关。
我使用Requests库来命中HTTP端点。 我想检查回复是否成功。
我目前正在这样做:
r = requests.get(url)
if 200 <= response.status_code <= 299:
# Do something here!
我可以使用简写,而不是对200到299之间的值进行丑陋的检查吗?
答案 0 :(得分:18)
The response has an ok
property。使用它。
@property
def ok(self):
"""Returns True if :attr:`status_code` is less than 400.
This attribute checks if the status code of the response is between
400 and 600 to see if there was a client error or a server error. If
the status code, is between 200 and 400, this will return True. This
is **not** a check to see if the response code is ``200 OK``.
"""
try:
self.raise_for_status()
except HTTPError:
return False
return True
答案 1 :(得分:1)
我是Python新手,但我认为最简单的方法是:
if response.ok:
# whatever
答案 2 :(得分:0)
用于检查请求是否成功的 pythonic 方法是(可选)引发带有
的异常#!/bin/bash
stdbuf -oL -eL libinput debug-events \
--device /dev/input/by-path/pci-0000:00:1f.0-platform-INT33D6:00-event |
grep SWITCH_TOGGLE |
while read -a fields; do
case ${fields[6]} in
0) systemctl stop iio-sensor-proxy.service;;
1) systemctl start iio-sensor-proxy.service;;
esac
done
EAFP:寻求宽恕比获得许可更容易:您应该按照预期的方式工作,如果操作中可能引发异常,则应予以捕获并处理该事实。