把下面的代碼放在requests_module.py文件中
# coding: utf-8
import requests
import logging
from requests.exceptions import *
class GetResponse():
def __init__(self, url, method='get'):
self.__url = url
self.__method = method.lower()
self.with_session = requests.session()
def get_response(self, session=False, *args, **kwargs): if self.__method == 'get' and session == False:
try:
__resp = requests.get(self.__url, *args, **kwargs)
except (MissingSchema, InvalidURL):
logging.error(u'請(qǐng)檢查url:%s 是否正確' % self.__url)
except ConnectionError:
logging.error(u'網(wǎng)絡(luò)連接失敗或接口響應(yīng)時(shí)間過(guò)長(zhǎng)')
else:
return __resp
elif self.__method == 'get' and session == True:
try:
__resp = self.with_session.get(self.__url, *args, **kwargs)
except (MissingSchema, InvalidURL):
logging.error(u'請(qǐng)檢查url:%s 是否正確' % self.__url)
except ConnectionError:
logging.error(u'網(wǎng)絡(luò)連接失敗或接口響應(yīng)時(shí)間過(guò)長(zhǎng)')
else:
return __resp
elif self.__method == 'post' and session == False:
try:
__resp = requests.post(self.__url, *args, **kwargs)
except (MissingSchema, InvalidURL):
logging.error(u'請(qǐng)檢查url:%s 是否正確' % self.__url)
except ConnectionError:
logging.error(u'網(wǎng)絡(luò)連接失敗或接口響應(yīng)時(shí)間過(guò)長(zhǎng)')
else:
return __resp
elif self.__method == 'post' and session == True:
try:
__resp = self.with_session.post(self.__url, *args, **kwargs)
except (MissingSchema, InvalidURL):
logging.error(u'請(qǐng)檢查url:%s 是否正確' % self.__url)
except ConnectionError:
logging.error(u'網(wǎng)絡(luò)連接失敗或接口響應(yīng)時(shí)間過(guò)長(zhǎng)')
else:
return __respclass AnalysisResponse(object):
"""
解析response:response為一大段字符串,該類(lèi)將這個(gè)大串字符串中有用的內(nèi)容提取出來(lái)
"""
def __init__(self, resp):
self.__resp = resp
@property
def Url(self):
__url = self.__resp.url
return __url
@property
def Status_code(self):
__status_code = self.__resp.status_code
return __status_code
@property
def Str_Content(self):
"""
返回string類(lèi)型的content
"""
__str_content = self.__resp.content
return __str_content
@property
def Dic_Content(self):
"""
將response轉(zhuǎn)換成字典后返回
"""
__dic_content = self.__resp.json()
return __dic_content
@property
def Headers(self):
__headers = self.__resp.headers
return __headers
@property
def Cookies(self):
__cookies = self.__resp.cookies
return __cookies
紅色字體的內(nèi)容就是發(fā)送的方法了,我們看到它會(huì)根據(jù)你傳入接口的http請(qǐng)求選擇發(fā)送方式,并且判斷了是否含有session,session可以省去你登錄的時(shí)候再去校驗(yàn)cookies。是不是對(duì)__xx不太熟悉?你需要復(fù)習(xí)前面的內(nèi)容了……自己看吧,你懶得翻,我懶得寫(xiě)。 不開(kāi)森
|