1. 程式人生 > 程式設計 >python requests response值判斷方式

python requests response值判斷方式

這段時間在技術上沒太多的思考的,只是碰到幾個蝦米小問題。 往往問題不大,也會致使你花心思去排解。

今遇到一個reqeusts返回值的一個問題,花了不短時間調,後來發現是reqeusts返回的物件也含有 魔法函式 處理。

我這邊的業務是cdn的重新整理預快取,對於該專案來說 http code 200,2xx,404 都是友好的。

#jb51.net

import requests
r = None
try:
 r = requests.get("https://jb51.net")
except:
 pass
if r:
 print "ok"

為什麼沒有輸出ok ? 按照常理來說,只要r不為 零值,就可以匹配到True. 但這次的返回是 <Response [404]>,為什麼404會引起 if r 判斷異常。

> type(r)

> requests.models.Response

看 requests的原始碼可以很容易分析出該問題。

#jb51.net

class Response(object):
 """The :class:`Response <Response>` object,which contains a
 server's response to an HTTP request.
 """

 __attrs__ = [
  '_content','status_code','headers','url','history','encoding','reason','cookies','elapsed','request'
 ]

 def __init__(self):
  super(Response,self).__init__()

  self._content = False
  self._content_consumed = False

  #: Integer Code of responded HTTP Status,e.g. 404 or 200.
  self.status_code = None

 def __repr__(self):
  return '<Response [%s]>' % (self.status_code)

 def __bool__(self):
  return self.ok

 @property
 def ok(self):
  try:
   self.raise_for_status()
  except HTTPError:
   return False
  return True

 def raise_for_status(self):
 ¦ """Raises stored :class:`HTTPError`,if one occurred."""

 ¦ http_error_msg = ''

 ¦ if 400 <= self.status_code < 500:
 ¦ ¦ http_error_msg = '%s Client Error: %s for url: %s' % (self.status_code,self.reason,self.url)

 ¦ elif 500 <= self.status_code < 600:
 ¦ ¦ http_error_msg = '%s Server Error: %s for url: %s' % (self.status_code,self.url)

 ¦ if http_error_msg:
 ¦ ¦ raise HTTPError(http_error_msg,response=self)

END.

以上這篇python requests response值判斷方式就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。