Hướng dẫn python requests raise exception if not 200 - Yêu cầu python nâng cao ngoại lệ nếu không phải là 200

Lưu ý: Bạn nên đi với response.raise_for_status() như được mô tả trong câu trả lời của Ian ở trên (anh ấy là một trong những người duy trì mô -đun requests).: You should rather go with response.raise_for_status() as described in Ian's answer above (he's one of the maintainers of the requests module).


Cách bạn xử lý tất cả điều này tùy thuộc vào những gì bạn coi là lỗi HTTP. Có mã trạng thái, nhưng không phải tất cả mọi thứ khác ngoài 200 nhất thiết có nghĩa là có một lỗi nào đó.

Như bạn đã nhận thấy, thư viện yêu cầu xem xét những điều đó chỉ là một khía cạnh khác của phản hồi HTTP và không nêu ra một ngoại lệ. Trạng thái HTTP 302 Ví dụ có nghĩa là Found, nhưng phản hồi không chứa cơ thể phản hồi mà là tiêu đề Location thay vào đó bạn cần phải làm theo để có được tài nguyên bạn thực sự muốn.

Vì vậy, bạn sẽ muốn xem xét

Fetching URL 'http://httpbin.org/user-agent'
{u'user-agent': u'python-requests/2.1.0 CPython/2.7.1 Darwin/11.4.2'}

Fetching URL 'http://httpbin.org/status/404'
Error: Unexpected response <Response [404]>

Fetching URL 'http://httpbin.org/status/500'
Error: Unexpected response <Response [500]>

Fetching URL 'httpx://invalid/url'
Error: No connection adapters were found for 'httpx://invalid/url'
0 và xử lý việc đó, trong khi bắt các lỗi giao thức thực tế với
Fetching URL 'http://httpbin.org/user-agent'
{u'user-agent': u'python-requests/2.1.0 CPython/2.7.1 Darwin/11.4.2'}

Fetching URL 'http://httpbin.org/status/404'
Error: Unexpected response <Response [404]>

Fetching URL 'http://httpbin.org/status/500'
Error: Unexpected response <Response [500]>

Fetching URL 'httpx://invalid/url'
Error: No connection adapters were found for 'httpx://invalid/url'
1. Khi bắt những người bạn thực sự nên bắt
Fetching URL 'http://httpbin.org/user-agent'
{u'user-agent': u'python-requests/2.1.0 CPython/2.7.1 Darwin/11.4.2'}

Fetching URL 'http://httpbin.org/status/404'
Error: Unexpected response <Response [404]>

Fetching URL 'http://httpbin.org/status/500'
Error: Unexpected response <Response [500]>

Fetching URL 'httpx://invalid/url'
Error: No connection adapters were found for 'httpx://invalid/url'
2, bởi vì đây là lớp cơ sở cho tất cả các ngoại lệ khác, mô -đun requests tăng lên.protocol errors with a
Fetching URL 'http://httpbin.org/user-agent'
{u'user-agent': u'python-requests/2.1.0 CPython/2.7.1 Darwin/11.4.2'}

Fetching URL 'http://httpbin.org/status/404'
Error: Unexpected response <Response [404]>

Fetching URL 'http://httpbin.org/status/500'
Error: Unexpected response <Response [500]>

Fetching URL 'httpx://invalid/url'
Error: No connection adapters were found for 'httpx://invalid/url'
1. When catching those you should actually catch
Fetching URL 'http://httpbin.org/user-agent'
{u'user-agent': u'python-requests/2.1.0 CPython/2.7.1 Darwin/11.4.2'}

Fetching URL 'http://httpbin.org/status/404'
Error: Unexpected response <Response [404]>

Fetching URL 'http://httpbin.org/status/500'
Error: Unexpected response <Response [500]>

Fetching URL 'httpx://invalid/url'
Error: No connection adapters were found for 'httpx://invalid/url'
2, because this is the base class for all other exceptions the requests module raises.

Vì vậy, đây là một ví dụ chứng minh cả ba trường hợp:

  • Sucessfull
    Fetching URL 'http://httpbin.org/user-agent'
    {u'user-agent': u'python-requests/2.1.0 CPython/2.7.1 Darwin/11.4.2'}
    
    Fetching URL 'http://httpbin.org/status/404'
    Error: Unexpected response <Response [404]>
    
    Fetching URL 'http://httpbin.org/status/500'
    Error: Unexpected response <Response [500]>
    
    Fetching URL 'httpx://invalid/url'
    Error: No connection adapters were found for 'httpx://invalid/url'
    
    4 Phản hồi
  • Yêu cầu và phản hồi thành công, nhưng trạng thái khác với 200
  • Lỗi giao thức (lược đồ không hợp lệ)
import requests

test_urls = ['http://httpbin.org/user-agent',
             'http://httpbin.org/status/404',
             'http://httpbin.org/status/500',
             'httpx://invalid/url']


def return_json(url):
    try:
        response = requests.get(url)

        # Consider any status other than 2xx an error
        if not response.status_code // 100 == 2:
            return "Error: Unexpected response {}".format(response)

        json_obj = response.json()
        return json_obj
    except requests.exceptions.RequestException as e:
        # A serious problem happened, like an SSLError or InvalidURL
        return "Error: {}".format(e)


for url in test_urls:
    print "Fetching URL '{}'".format(url)
    print return_json(url)
    print

Output:

Fetching URL 'http://httpbin.org/user-agent'
{u'user-agent': u'python-requests/2.1.0 CPython/2.7.1 Darwin/11.4.2'}

Fetching URL 'http://httpbin.org/status/404'
Error: Unexpected response <Response [404]>

Fetching URL 'http://httpbin.org/status/500'
Error: Unexpected response <Response [500]>

Fetching URL 'httpx://invalid/url'
Error: No connection adapters were found for 'httpx://invalid/url'

Cũng có thể có một ngoại lệ được nêu ra bởi

Fetching URL 'http://httpbin.org/user-agent'
{u'user-agent': u'python-requests/2.1.0 CPython/2.7.1 Darwin/11.4.2'}

Fetching URL 'http://httpbin.org/status/404'
Error: Unexpected response <Response [404]>

Fetching URL 'http://httpbin.org/status/500'
Error: Unexpected response <Response [500]>

Fetching URL 'httpx://invalid/url'
Error: No connection adapters were found for 'httpx://invalid/url'
6 nếu bạn nhận được phản hồi thành công, nhưng đơn giản là nó không phải là JSON - vì vậy bạn cũng có thể muốn giải thích cho điều đó.


Lưu ý: bit

Fetching URL 'http://httpbin.org/user-agent'
{u'user-agent': u'python-requests/2.1.0 CPython/2.7.1 Darwin/11.4.2'}

Fetching URL 'http://httpbin.org/status/404'
Error: Unexpected response <Response [404]>

Fetching URL 'http://httpbin.org/status/500'
Error: Unexpected response <Response [500]>

Fetching URL 'httpx://invalid/url'
Error: No connection adapters were found for 'httpx://invalid/url'
7 hoạt động như thế này: toán tử
Fetching URL 'http://httpbin.org/user-agent'
{u'user-agent': u'python-requests/2.1.0 CPython/2.7.1 Darwin/11.4.2'}

Fetching URL 'http://httpbin.org/status/404'
Error: Unexpected response <Response [404]>

Fetching URL 'http://httpbin.org/status/500'
Error: Unexpected response <Response [500]>

Fetching URL 'httpx://invalid/url'
Error: No connection adapters were found for 'httpx://invalid/url'
8 thực hiện một phân chia sàn được gọi là, vì vậy nó làm tròn đến số nguyên tiếp theo (đây là hành vi mặc định cho
Fetching URL 'http://httpbin.org/user-agent'
{u'user-agent': u'python-requests/2.1.0 CPython/2.7.1 Darwin/11.4.2'}

Fetching URL 'http://httpbin.org/status/404'
Error: Unexpected response <Response [404]>

Fetching URL 'http://httpbin.org/status/500'
Error: Unexpected response <Response [500]>

Fetching URL 'httpx://invalid/url'
Error: No connection adapters were found for 'httpx://invalid/url'
9 trong Python 2.x, nhưng không phải là Python 3.x, mà đã thay đổi
Fetching URL 'http://httpbin.org/user-agent'
{u'user-agent': u'python-requests/2.1.0 CPython/2.7.1 Darwin/11.4.2'}

Fetching URL 'http://httpbin.org/status/404'
Error: Unexpected response <Response [404]>

Fetching URL 'http://httpbin.org/status/500'
Error: Unexpected response <Response [500]>

Fetching URL 'httpx://invalid/url'
Error: No connection adapters were found for 'httpx://invalid/url'
9 để thực hiện phân chia điểm nổi). Vì vậy,
    r = requests.get(self.url(False))
    if r.status_code != 200:
        raise requests.ConnectionError("Expected status code 200, but got {}".format(page.status_code))
1 đúng với tất cả các mã
    r = requests.get(self.url(False))
    if r.status_code != 200:
        raise requests.ConnectionError("Expected status code 200, but got {}".format(page.status_code))
2.
: The
Fetching URL 'http://httpbin.org/user-agent'
{u'user-agent': u'python-requests/2.1.0 CPython/2.7.1 Darwin/11.4.2'}

Fetching URL 'http://httpbin.org/status/404'
Error: Unexpected response <Response [404]>

Fetching URL 'http://httpbin.org/status/500'
Error: Unexpected response <Response [500]>

Fetching URL 'httpx://invalid/url'
Error: No connection adapters were found for 'httpx://invalid/url'
7 bit works like this: The
Fetching URL 'http://httpbin.org/user-agent'
{u'user-agent': u'python-requests/2.1.0 CPython/2.7.1 Darwin/11.4.2'}

Fetching URL 'http://httpbin.org/status/404'
Error: Unexpected response <Response [404]>

Fetching URL 'http://httpbin.org/status/500'
Error: Unexpected response <Response [500]>

Fetching URL 'httpx://invalid/url'
Error: No connection adapters were found for 'httpx://invalid/url'
8 operator does a so called floor division, so it rounds down to the next integer (this is the default behavior for the
Fetching URL 'http://httpbin.org/user-agent'
{u'user-agent': u'python-requests/2.1.0 CPython/2.7.1 Darwin/11.4.2'}

Fetching URL 'http://httpbin.org/status/404'
Error: Unexpected response <Response [404]>

Fetching URL 'http://httpbin.org/status/500'
Error: Unexpected response <Response [500]>

Fetching URL 'httpx://invalid/url'
Error: No connection adapters were found for 'httpx://invalid/url'
9 in Python 2.x, but not Python 3.x, which changed
Fetching URL 'http://httpbin.org/user-agent'
{u'user-agent': u'python-requests/2.1.0 CPython/2.7.1 Darwin/11.4.2'}

Fetching URL 'http://httpbin.org/status/404'
Error: Unexpected response <Response [404]>

Fetching URL 'http://httpbin.org/status/500'
Error: Unexpected response <Response [500]>

Fetching URL 'httpx://invalid/url'
Error: No connection adapters were found for 'httpx://invalid/url'
9 to do floating point division). So
    r = requests.get(self.url(False))
    if r.status_code != 200:
        raise requests.ConnectionError("Expected status code 200, but got {}".format(page.status_code))
1 holds true for all
    r = requests.get(self.url(False))
    if r.status_code != 200:
        raise requests.ConnectionError("Expected status code 200, but got {}".format(page.status_code))
2 codes.

Xin chào, tôi thường mong đợi yêu cầu có mã trạng thái 200 và nếu tôi không có nhiều điều tôi có thể làm (nghiêm túc khi máy chủ trả về với lỗi 500, tôi sẽ không thể làm gì đó). Vì vậy, tôi cần phải viết mã như thế này:
I often expect the request to have status code 200 and if it doesn't there isn't much I can do about (seriously when the server returns with error 500, I won't be able to do something). So I need to write code like this:

    r = requests.get(self.url(False))
    if r.status_code != 200:
        raise requests.ConnectionError("Expected status code 200, but got {}".format(page.status_code))

Tôi nghĩ rằng một kwarg được gọi là cho phép_status_codes sẽ rất thuận tiện. Nó có thể được thực hiện như thế này: Theo mặc định, nó là

    r = requests.get(self.url(False))
    if r.status_code != 200:
        raise requests.ConnectionError("Expected status code 200, but got {}".format(page.status_code))
3.
    r = requests.get(self.url(False))
    if r.status_code != 200:
        raise requests.ConnectionError("Expected status code 200, but got {}".format(page.status_code))
3 và một danh sách trống hoặc tuple có nghĩa là cho phép tất cả các mã trạng thái. Nó có thể là một số nguyên, danh sách, tuple hoặc enum. Nếu nó là một số nguyên, chỉ cho phép mã trạng thái cụ thể này. Trong trường hợp đó là danh sách hoặc tuple, chỉ các mã trạng thái nằm trong danh sách/tuple mới được phép. Danh sách có thể có số nguyên và/hoặc enums. Enums nên linh hoạt hơn một chút. Chẳng hạn, nếu tôi muốn cho phép tất cả các yêu cầu "thành công" (2xx), tôi có thể viết: Cho phép_status_codes = requests.allow_success, sẽ ném một ngoại lệ trừ khi mã trạng thái là 2xx. Nếu tôi chỉ muốn không cho phép các lỗi máy chủ (và do đó xử lý các lỗi không được xác thực), tôi chỉ có thể viết cho phép Tất nhiên nên có rất nhiều enum bao gồm các trường hợp cụ thể. Và người ta cũng có thể sử dụng nó kết hợp trong danh sách (ví dụ:
    r = requests.get(self.url(False))
    if r.status_code != 200:
        raise requests.ConnectionError("Expected status code 200, but got {}".format(page.status_code))
5). Nếu mã trạng thái không được phép,
    r = requests.get(self.url(False))
    if r.status_code != 200:
        raise requests.ConnectionError("Expected status code 200, but got {}".format(page.status_code))
6 sẽ được nâng lên.
By default it is
    r = requests.get(self.url(False))
    if r.status_code != 200:
        raise requests.ConnectionError("Expected status code 200, but got {}".format(page.status_code))
3.
    r = requests.get(self.url(False))
    if r.status_code != 200:
        raise requests.ConnectionError("Expected status code 200, but got {}".format(page.status_code))
3, and an empty list or tuple means allow all status codes. It may be an integer, list, tuple, or enum. If it is an integer, only allow this specific status code. In case it is a list or tuple, only status codes that are inside of the list/tuple are allowed. The list may have integers and/or enums. Enums should be a little bit more flexible.
For instance, if I wanted to allow all "successful" (2xx) requests, I could write: allowed_status_codes=requests.ALLOW_SUCCESS, which will throw an exception unless the status code is 2xx. If I only wanted to disallow server errors (and thus handle not authenticated errors), I could simply write allowed_status_codes=requests.DISALLOW_SERVER_ERROR, which will raise an exception if the server code is 5xx.
Of course there should be lots of enums that cover specific cases. And one should also be able to use it combined within a list (e.g.
    r = requests.get(self.url(False))
    if r.status_code != 200:
        raise requests.ConnectionError("Expected status code 200, but got {}".format(page.status_code))
5).
If the status code isn't allowed, a
    r = requests.get(self.url(False))
    if r.status_code != 200:
        raise requests.ConnectionError("Expected status code 200, but got {}".format(page.status_code))
6 will be raised.


Mặc dù tôi đã đề cập đến Enums, tôi không nói về các giá trị được liệt kê của Python 3.4. Tôi đã nói thay vì các hằng số. Enums (hằng số) có thể được thực hiện như thế này:

#request model.

ALLOW_SUCCESS = AllowSuccessEnum()
# other enums

class RequestEnum(object):
     def is_status_code_allowed(status_code):
         raise NotImplementedError

class AllowSuccessEnum(RequestEnum):
    def is_status_code_allowed(status_code):
        # return false unless status code is 2xx

Làm cách nào để kiểm tra phản hồi của tôi 200 trong Python?

Kiểm tra nếu phản hồi là 200 Python..
Nếu resp.status_code == 200:.
In ('OK!').
In ('Boo!').

Những yêu cầu gì ngoại lệ ConnectionError?

Lỗi kết nối ngoại lệerRor - Điều này sẽ được nêu ra, nếu có bất kỳ lỗi kết nối nào.Ví dụ: mạng không thành công, lỗi DNS để thư viện yêu cầu sẽ tăng ngoại lệ ConnectionError.Phản ứng.RAISE_FOR_STATUS () - Dựa trên mã trạng thái, tức là 401, 404 Nó sẽ tăng httperror cho URL được yêu cầu.This will be raised, if there is any connection error. For example, the network failed, DNS error so the Request library will raise ConnectionError exception. Response. raise_for_status() − Based on status code i.e. 401, 404 it will raise HTTPError for the url requested.

Làm thế nào để Python xử lý httperror?

Làm thế nào để bắt một httperror trong Python..
Trả lời = Yêu cầu.Nhận ("https://httpbin.org/status/404").
phản ứng.RAISE_FOR_STATUS () Tăng Httperror khỏi phản hồi ..
ngoại trừ các yêu cầu.Httperror là ngoại lệ:.
print(exception).

Yêu cầu Python có bị phản đối không?

Khi chúng tôi bước vào năm thứ ba của Python 2.7 đạt đến cuối đời, các yêu cầu đã quyết định đã đến lúc bắt đầu không phản đối sự hỗ trợ của chúng tôi.Mặc dù chúng tôi vẫn chưa xác nhận một ngày, chúng tôi muốn cung cấp thông báo sớm rằng điều này sẽ đến vào một thời điểm nào đó vào năm 2022.Requests has decided it's time to start deprecating our support. While we have yet to confirm a date, we want to provide early notice that this is coming at some point in 2022.