- #发送POST请求并保存Cookie
- #@url 被请求的URL地址(必需)
- #@data POST参数,可以是字符串或字典(必需)
- #@timeout 超时时间默认1800秒
- #return string
- def __http_post_cookie(self,url,p_data,timeout=1800):
- cookie_file = './' + self.__get_md5(self.__BT_PANEL) + '.cookie';
- if sys.version_info[0] == 2:
- #Python2
- import urllib,urllib2,ssl,cookielib
- #创建cookie对象
- cookie_obj = cookielib.MozillaCookieJar(cookie_file)
- #加载已保存的cookie
- if os.path.exists(cookie_file):cookie_obj.load(cookie_file,ignore_discard=True,ignore_expires=True)
- ssl._create_default_https_context = ssl._create_unverified_context
- data = urllib.urlencode(p_data)
- req = urllib2.Request(url, data)
- opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_obj))
- response = opener.open(req,timeout=timeout)
- #保存cookie
- cookie_obj.save(ignore_discard=True, ignore_expires=True)
- return response.read()
- else:
- #Python3
- import urllib.request,ssl,http.cookiejar
- cookie_obj = http.cookiejar.MozillaCookieJar(cookie_file)
- if os.path.exists(cookie_file):
- cookie_obj.load(cookie_file,ignore_discard=True,ignore_expires=True)
- handler = urllib.request.HTTPCookieProcessor(cookie_obj)
- data = urllib.parse.urlencode(p_data).encode('utf-8')
- req = urllib.request.Request(url, data)
- opener = urllib.request.build_opener(handler)
- response = opener.open(req,timeout = timeout)
- cookie_obj.save(ignore_discard=True, ignore_expires=True)
- result = response.read()
- if type(result) == bytes: result = result.decode('utf-8')
- return result
复制代码 修复一下官方接口的小bug,在类方法__http_post_cookie处加上一个文件判断,存在时读取文件,不存在时请求。避免了首次初始化运行不了的尴尬情况
python3和python2通用的,可以自行修复
|