Urllib2 替换 Pycurl
调试百度云服务,给IOS手机推送消息,突然发现由于SAE不支持(据说bae也不支持)pycurl,所以原始sdk不能直接用。因此将替换方法记录下来。 官方貌似没有给出python的sdk,应该趁还在百度工作,给提提建议。遇到了些问题,参考php的sdk解决了。 1、pycurl不支持,使用urllib2替换 原始代码:RequestCore.py def handle_request(self): curl_handle = pycurl.Curl() # set default options. curl_handle.setopt(pycurl.URL, self.request_url) curl_handle.setopt(pycurl.REFERER, self.request_url) curl_handle.setopt(pycurl.USERAGENT, self.useragent) curl_handle.setopt(pycurl.TIMEOUT, 5184000) curl_handle.setopt(pycurl.CONNECTTIMEOUT, 120) curl_handle.setopt(pycurl.HEADER, True) # curl_handle.setopt(pycurl.VERBOSE, 1) curl_handle.setopt(pycurl.FOLLOWLOCATION, 1) curl_handle.setopt(pycurl.MAXREDIRS, 5) if(self.request_headers and len(self.request_headers) > 0): tmplist = list() for(key, value) in self.request_headers.items(): tmplist.append(key + ':' + value) curl_handle.setopt(pycurl.HTTPHEADER, tmplist) #目前只需支持POST curl_handle.setopt(pycurl.HTTPPROXYTUNNEL, 1) curl_handle.setopt(pycurl.POSTFIELDS, self.request_body) response = StringIO.StringIO() curl_handle.setopt(pycurl.WRITEFUNCTION, response.write) curl_handle.perform() self.response_code = curl_handle.getinfo(curl_handle.HTTP_CODE) header_size = curl_handle.getinfo(curl_handle.HEADER_SIZE) resp_str = response.getvalue() self.response_headers = resp_str[0 : header_size] self.response_body = resp_str[header_size : ] response.close() curl_handle.close() 修改为: def handle_request(self): url = self.request_url headers = dict() headers['HTTP_REFERER'] = self.request_url request = urllib2.Request(url, self.request_body, headers) f = urllib2.urlopen(request) self.response_code = f.getcode() self.response_headers = f.info() self.response_body = f.read() 2、信息返回推送成功,手机却收不到 (1)据说的确有丢信息的几率,哎,百度怎么搞的 (2)需要在python的sdk中添加开发参数,从PHP的SDK中查看出来的: 在Channel.py中添加类变量 DEPLOY_STATUS = 'deploy_status' 发送demo c = Channel.Channel(apiKey, secretKey) push_type = 3 optional = dict() optional[Channel.Channel.MESSAGE_TYPE] = 1 optional[Channel.Channel.DEVICE_TYPE] = 4 optional[Channel.Channel.DEPLOY_STATUS] = 1 message = "{'title':'baidu push','description':'message from python sdk'}" message_key = "key1" ret = c.pushMessage(push_type, message, message_key, optional) 祝大家成功!





