Meine Frage ist eng verwandt mit diese .
Ich verwende die Requests-Bibliothek, um einen HTTP-Endpunkt zu erreichen. Ich möchte überprüfen, ob die Antwort erfolgreich ist.
Ich mache gerade folgendes:
r = requests.get(url)
if 200 <= response.status_code <= 299:
# Do something here!
Gibt es eine Kurzform, die ich verwenden kann, anstatt diese hässliche Prüfung auf Werte zwischen 200 und 299 durchzuführen?
Die Antwort hat eine ok
-Eigenschaft . Verwende das.
@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
Ich bin ein Python Neuling, aber ich denke, der einfachste Weg ist:
if response.ok:
# whatever