def _request(self, method, url_or_endpoint, **kwargs): if not url_or_endpoint.startswith(('http://', 'https://')): api_base_url = kwargs.pop('api_base_url', self.API_BASE_URL) url = '{base}{endpoint}'.format(base=api_base_url, endpoint=url_or_endpoint) else: url = url_or_endpoint # 群发消息上传视频接口地址 HTTPS 证书错误,暂时忽略证书验证 if url.startswith('https://file.api.weixin.qq.com'): kwargs['verify'] = False if 'params' not in kwargs: kwargs['params'] = {} if isinstance(kwargs['params'], dict) and \ 'access_token' not in kwargs['params']: kwargs['params']['access_token'] = self.access_token if isinstance(kwargs.get('data', ''), dict): body = json.dumps(kwargs['data'], ensure_ascii=False) body = body.encode('utf-8') kwargs['data'] = body res = requests.request(method=method, url=url, **kwargs) try: res.raise_for_status() except requests.RequestException as reqe: raise WeChatClientException(errcode=None, errmsg=None, client=self, request=reqe.request, response=reqe.response) return self._handle_result(res, method, url, **kwargs)
def wechat_api_mock(client, request, *args, **kwargs): url = urlparse(request.url) path = url.path.replace('/cgi-bin/', '').replace('/', '_') if path.startswith('_'): path = path[1:] res_file = os.path.join(_FIXTURE_PATH, '%s.json' % path) content = { 'errcode': 99999, 'errmsg': 'can not find fixture %s' % res_file, } headers = { 'Content-Type': 'application/json' } try: with open(res_file, 'rb') as f: content = f.read().decode('utf-8') except (IOError, ValueError) as e: content['errmsg'] = 'Loads fixture {0} failed, error: {1}'.format( res_file, e ) content = json.dumps(content) buffer = StringIO(content) resp = HTTPResponse( request, 200, headers=headers, buffer=buffer, ) future = Future() future.set_result(resp) return future
def _request(self, method, url_or_endpoint, **kwargs): if not url_or_endpoint.startswith(('http://', 'https://')): url = '{base}{endpoint}'.format( base=self.API_BASE_URL, endpoint=url_or_endpoint ) else: url = url_or_endpoint if isinstance(kwargs.get('data', ''), dict): body = json.dumps(kwargs['data'], ensure_ascii=False) body = body.encode('utf-8') kwargs['data'] = body res = requests.request( method=method, url=url, **kwargs ) res.raise_for_status() result = res.json() if 'errcode' in result and result['errcode'] != 0: errcode = result['errcode'] errmsg = result['errmsg'] raise WeChatOAuthException(errcode, errmsg) return result
def _request(self, method, url_or_endpoint, **kwargs): if not url_or_endpoint.startswith(("http://", "https://")): api_base_url = kwargs.pop("api_base_url", self.API_BASE_URL) url = "{base}{endpoint}".format(base=api_base_url, endpoint=url_or_endpoint) else: url = url_or_endpoint # 群发消息上传视频接口地址 HTTPS 证书错误,暂时忽略证书验证 if url.startswith("https://file.api.weixin.qq.com"): kwargs["verify"] = False if "params" not in kwargs: kwargs["params"] = {} if isinstance(kwargs["params"], dict) and "access_token" not in kwargs["params"]: kwargs["params"]["access_token"] = self.access_token if isinstance(kwargs.get("data", ""), dict): body = json.dumps(kwargs["data"], ensure_ascii=False) body = body.encode("utf-8") kwargs["data"] = body res = requests.request(method=method, url=url, **kwargs) try: res.raise_for_status() except requests.RequestException as reqe: raise WeChatClientException( errcode=None, errmsg=None, client=self, request=reqe.request, response=reqe.response ) return self._handle_result(res, method, url, **kwargs)
def add(self, media_type, media_file, title=None, introduction=None): """ 新增其它类型永久素材 详情请参考 http://mp.weixin.qq.com/wiki/14/7e6c03263063f4813141c3e17dd4350a.html :param media_type: 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb) :param media_file: 要上传的文件,一个 File-object :param title: 视频素材标题,仅上传视频素材时需要 :param introduction: 视频素材简介,仅上传视频素材时需要 :return: 返回的 JSON 数据包 """ params = { 'access_token': self.access_token, 'type': media_type } if media_type == 'video': assert title, 'Video title must be set' assert introduction, 'Video introduction must be set' description = { 'title': title, 'introduction': introduction } params['description'] = json.dumps(description) return self._post( url='http://file.api.weixin.qq.com/cgi-bin/material/add_material', params=params, files={ 'media': media_file } )
def get(self, media_id): """ 获取永久素材 详情请参考 http://mp.weixin.qq.com/wiki/4/b3546879f07623cb30df9ca0e420a5d0.html :param media_id: 素材的 media_id :return: 图文素材返回图文列表,其它类型为素材的内容 """ res = requests.post( url='https://api.weixin.qq.com/cgi-bin/material/get_material', params={ 'access_token': self.access_token }, data=json.dumps({ 'media_id': media_id }) ) # 返回有中文会乱码 res.encoding = 'utf-8' content_type = res.headers['Content-Type'].lower() if content_type in ('application/json', 'application/javascript', 'application/x-javascript', 'text/javascript', 'text/json'): # news item return return res.json().get('news_item', []) return res
def _request(self, method, url_or_endpoint, **kwargs): if not url_or_endpoint.startswith(('http://', 'https://')): api_base_url = kwargs.pop('api_base_url', self.API_BASE_URL) url = '{base}{endpoint}'.format( base=api_base_url, endpoint=url_or_endpoint ) else: url = url_or_endpoint if 'params' not in kwargs: kwargs['params'] = {} if 'access_token' not in kwargs['params']: kwargs['params']['access_token'] = self.access_token if isinstance(kwargs.get('data', ''), dict): body = json.dumps(kwargs['data'], ensure_ascii=False) body = body.encode('utf-8') kwargs['data'] = body res = requests.request( method=method, url=url, **kwargs ) res.raise_for_status() result = res.json() return self._handle_result(result, method, url, **kwargs)
def side_effect(*args, **kwargs): path = urlparse(url).path.replace('/cgi-bin/', '').replace('/', '_') if path.startswith('_'): path = path[1:] res_file = os.path.join(_FIXTURE_PATH, '%s.json' % path) content = { 'errcode': 99999, 'errmsg': 'can not find fixture %s' % res_file, } headers = { 'Content-Type': 'application/json' } try: with open(res_file, 'rb') as f: content = f.read() except (IOError, ValueError) as e: content['errmsg'] = 'Loads fixture {0} failed, error: {1}'.format( res_file, e ) content = json.dumps(content) if isinstance(content, six.text_type): content = content.encode('utf-8') future = asyncio.Future(loop=asyncio.get_event_loop()) future.set_result(content) return future
def _request(self, method, url_or_endpoint, **kwargs): if not url_or_endpoint.startswith(('http://', 'https://')): url = '{base}{endpoint}'.format(base=self.API_BASE_URL, endpoint=url_or_endpoint) else: url = url_or_endpoint if isinstance(kwargs.get('data', ''), dict): body = json.dumps(kwargs['data'], ensure_ascii=False) body = body.encode('utf-8') kwargs['data'] = body res = requests.request(method=method, url=url, **kwargs) try: res.raise_for_status() except requests.RequestException as reqe: raise WeChatOAuthException(errcode=None, errmsg=None, client=self, request=reqe.request, response=reqe.response) res.encoding = 'UTF-8' result = res.json() if 'errcode' in result and result['errcode'] != 0: errcode = result['errcode'] errmsg = result['errmsg'] raise WeChatOAuthException(errcode, errmsg, client=self, request=res.request, response=res) return result
def _request(self, method, url_or_endpoint, **kwargs): http_client = AsyncHTTPClient() if not url_or_endpoint.startswith(('http://', 'https://')): api_base_url = kwargs.pop('api_base_url', self.API_BASE_URL) url = '{base}{endpoint}'.format(base=api_base_url, endpoint=url_or_endpoint) else: url = url_or_endpoint headers = {} params = kwargs.pop('params', {}) if 'access_token' not in params: params['access_token'] = self.access_token params = urlencode(dict((k, to_binary(v)) for k, v in params.items())) url = '{0}?{1}'.format(url, params) data = kwargs.get('data') files = kwargs.get('files') if files: from requests.models import RequestEncodingMixin from requests.utils import super_len body, content_type = RequestEncodingMixin._encode_files( files, data) headers['Content-Type'] = content_type headers['Content-Length'] = super_len(body) else: if isinstance(data, dict): body = json.dumps(data, ensure_ascii=False) body = body.encode('utf-8') else: body = data result_processor = kwargs.pop('result_processor', None) timeout = kwargs.get('timeout', self.timeout) req = HTTPRequest(url=url, method=method.upper(), headers=headers, body=body, request_timeout=timeout) res = yield http_client.fetch(req) if res.error is not None: raise WeChatClientException(errcode=None, errmsg=None, client=self, request=req, response=res) result = self._handle_result(res, method, url, result_processor, **kwargs) raise Return(result)
def _request(self, method, url_or_endpoint, **kwargs): if not url_or_endpoint.startswith(('http://', 'https://')): api_base_url = kwargs.pop('api_base_url', self.API_BASE_URL) url = '{base}{endpoint}'.format( base=api_base_url, endpoint=url_or_endpoint ) else: url = url_or_endpoint # 群发消息上传视频接口地址 HTTPS 证书错误,暂时忽略证书验证 if url.startswith('https://file.api.weixin.qq.com'): kwargs['verify'] = False if 'params' not in kwargs: kwargs['params'] = {} if isinstance(kwargs['params'], dict) and \ 'access_token' not in kwargs['params']: kwargs['params']['access_token'] = self.access_token if isinstance(kwargs.get('data', ''), dict): body = json.dumps(kwargs['data'], ensure_ascii=False) body = body.encode('utf-8') kwargs['data'] = body kwargs['timeout'] = kwargs.get('timeout', self.timeout) result_processor = kwargs.pop('result_processor', None) res = requests.request( method=method, url=url, **kwargs ) try: res.raise_for_status() except requests.RequestException as reqe: raise WeChatClientException( errcode=None, errmsg=None, client=self, request=reqe.request, response=reqe.response ) return self._handle_result( res, method, url, result_processor, **kwargs )
def _request(self, method, url_or_endpoint, **kwargs): if not url_or_endpoint.startswith(('http://', 'https://')): api_base_url = kwargs.pop('api_base_url', self.API_BASE_URL) url = '{base}{endpoint}'.format(base=api_base_url, endpoint=url_or_endpoint) else: url = url_or_endpoint if 'params' not in kwargs: kwargs['params'] = {} if 'access_token' not in kwargs['params']: kwargs['params']['access_token'] = self.access_token if isinstance(kwargs.get('data', ''), dict): body = json.dumps(kwargs['data'], ensure_ascii=False) body = body.encode('utf-8') kwargs['data'] = body res = requests.request(method=method, url=url, **kwargs) res.raise_for_status() result = res.json() return self._handle_result(result, method, url, **kwargs)
def get(self, media_id): """ 获取永久素材 详情请参考 http://mp.weixin.qq.com/wiki/4/b3546879f07623cb30df9ca0e420a5d0.html :param media_id: 素材的 media_id :return: 图文素材返回图文列表,其它类型为素材的内容 """ res = requests.post( url='https://api.weixin.qq.com/cgi-bin/material/get_material', params={'access_token': self.access_token}, data=json.dumps({'media_id': media_id})) # 返回有中文会乱码 res.encoding = 'utf-8' content_type = res.headers['Content-Type'].lower() if content_type in ('application/json', 'application/javascript', 'application/x-javascript', 'text/javascript', 'text/json'): # news item return return res.json().get('news_item', []) return res
def set(self, key, value, ttl=None): if value is None: return key = self.key_name(key) value = json.dumps(value) self.mc.set(key, value)
def _request(self, method, url_or_endpoint, **kwargs): http_client = AsyncHTTPClient() if not url_or_endpoint.startswith(('http://', 'https://')): api_base_url = kwargs.pop('api_base_url', self.API_BASE_URL) url = '{base}{endpoint}'.format( base=api_base_url, endpoint=url_or_endpoint ) else: url = url_or_endpoint headers = {} params = kwargs.pop('params', {}) if 'access_token' not in params: params['access_token'] = self.access_token params = urlencode(dict((k, to_binary(v)) for k, v in params.items())) url = '{0}?{1}'.format(url, params) data = kwargs.get('data') files = kwargs.get('files') if files: from requests.models import RequestEncodingMixin from requests.utils import super_len body, content_type = RequestEncodingMixin._encode_files( files, data ) headers['Content-Type'] = content_type headers['Content-Length'] = super_len(body) else: if isinstance(data, dict): body = json.dumps(data, ensure_ascii=False) body = body.encode('utf-8') else: body = data result_processor = kwargs.pop('result_processor', None) timeout = kwargs.get('timeout', self.timeout) req = HTTPRequest( url=url, method=method.upper(), headers=headers, body=body, request_timeout=timeout ) res = yield http_client.fetch(req) if res.error is not None: raise WeChatClientException( errcode=None, errmsg=None, client=self, request=req, response=res ) result = self._handle_result( res, method, url, result_processor, **kwargs ) raise Return(result)