简体   繁体   中英

Python Requests HTTP sub-codes response

In the Requests module of Python, we can check the response of a request as below:

>>> resp = requests.get("https://stackoverflow.com")
>>> resp.status_code == 200
True
>>> resp.status_code == requests.codes.OK
True
>>> 

What can I do if I just need to check if the response that came, is a part of the HTTP sub-codes , viz.,

1xx (Informational responses)

2xx (Success)

3xx (Redirection)

4xx (Client errors)

5xx (Server errors)

They will always be a part of HTTP sub-codes response. I cant think of a time where it would be different. Check the status with resp.status_code like you are doing and Write a bunch of if stmts to make the code do what you want with it. :)

I would do the following to do what you might need.

def convert_to_xx(status_code):
    m = re.match(r'(?P<code>\d{1})\.*', str(status_code))
    return m.group('code') + "xx"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM