2017-11-06 17 views
1

제 질문은 밀접하게 this one과 관련 있습니다.요청 - 성공 메시지를 받고 있는지 확인하는 방법은 무엇입니까?

요청 라이브러리를 사용하여 HTTP 끝점에 도달했습니다. 응답이 성공했는지 확인하고 싶습니다.

나는 현재이 일을하고있다 :

r = requests.get(url) 
if 200 <= response.status_code <= 299: 
    # Do something here! 

대신 200과 299 사이의 값 추한 확인, 내가 사용할 수있는 속기가 있다는거야?

+1

당신은'r.raise_for_status()'를 사용할 수 있지만, 당신이 가진 것은보기가 어렵습니다. – kindall

답변

4

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 
+0

3xx 리디렉션 범위는 질문의 코드와 달리 괜찮다고 계산합니다. – user2357112

+1

'요청 '이 리디렉션을 따르므로 일반적으로 어쨌든 300 범위의 상태가 표시되지 않을 것이라고 생각합니다. 리디렉션 된 URL의 상태가 표시됩니다. – kindall