<commit_before># -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import sys
import time
import inspect

import six
import requests

from wechatpy.session.memorystorage import MemoryStorage
from wechatpy._compat import json, get_querystring
from wechatpy.exceptions import WeChatClientException, APILimitedException
from wechatpy.client.api.base import BaseWeChatAPI


def _is_api_endpoint(obj):
    return isinstance(obj, BaseWeChatAPI)


class BaseWeChatClient(object):

    API_BASE_URL = ''

    def __new__(cls, *args, **kwargs):
        self = super(BaseWeChatClient, cls).__new__(cls)
        if sys.version_info[:2] == (2, 6):
            import copy
            # Python 2.6 inspect.gemembers bug workaround
            # http://bugs.python.org/issue1785
            for _class in cls.__mro__:
                if issubclass(_class, BaseWeChatClient):
                    for name, api in _class.__dict__.items():
                        if isinstance(api, BaseWeChatAPI):
                            api = copy.deepcopy(api)
                            api._client = self
                            setattr(self, name, api)
        else:
            api_endpoints = inspect.getmembers(self, _is_api_endpoint)
            for name, api in api_endpoints:
                api_cls = type(api)
                api = api_cls(self)
                setattr(self, name, api)
        return self

    def __init__(self, access_token=None, session=None):
        self.expires_at = None
        self.session = session or MemoryStorage()

        if isinstance(session, six.string_types):
            from shove import Shove
            from wechatpy.session.shovestorage import ShoveStorage

            querystring = get_querystring(session)
            prefix = querystring.get('prefix', ['wechatpy'])[0]

            shove = Shove(session)
            storage = ShoveStorage(shove, prefix)
            self.session = storage

        self.session.set('access_token', access_token)

    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 _handle_result(self, res, method=None, url=None, **kwargs):
        res.encoding = 'utf-8'
        result = res.json()
        if 'base_resp' in result:
            # Different response in device APIs. Fuck tencent!
            result = result['base_resp']
        if 'errcode' in result:
            result['errcode'] = int(result['errcode'])

        if 'errcode' in result and result['errcode'] != 0:
            errcode = result['errcode']
            errmsg = result['errmsg']
            if errcode == 42001:
                # access_token expired, fetch a new one and retry request
                self.fetch_access_token()
                kwargs['params']['access_token'] = self.session.get(
                    'access_token'
                )
                return self._request(<commit_msg>Update WeChatClient retry fetch access token error codes<commit_after># -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import sys
import time
import inspect

import six
import requests

from wechatpy.session.memorystorage import MemoryStorage
from wechatpy._compat import json, get_querystring
from wechatpy.exceptions import WeChatClientException, APILimitedException
from wechatpy.client.api.base import BaseWeChatAPI


def _is_api_endpoint(obj):
    return isinstance(obj, BaseWeChatAPI)


class BaseWeChatClient(object):

    API_BASE_URL = ''

    def __new__(cls, *args, **kwargs):
        self = super(BaseWeChatClient, cls).__new__(cls)
        if sys.version_info[:2] == (2, 6):
            import copy
            # Python 2.6 inspect.gemembers bug workaround
            # http://bugs.python.org/issue1785
            for _class in cls.__mro__:
                if issubclass(_class, BaseWeChatClient):
                    for name, api in _class.__dict__.items():
                        if isinstance(api, BaseWeChatAPI):
                            api = copy.deepcopy(api)
                            api._client = self
                            setattr(self, name, api)
        else:
            api_endpoints = inspect.getmembers(self, _is_api_endpoint)
            for name, api in api_endpoints:
                api_cls = type(api)
                api = api_cls(self)
                setattr(self, name, api)
        return self

    def __init__(self, access_token=None, session=None):
        self.expires_at = None
        self.session = session or MemoryStorage()

        if isinstance(session, six.string_types):
            from shove import Shove
            from wechatpy.session.shovestorage import ShoveStorage

            querystring = get_querystring(session)
            prefix = querystring.get('prefix', ['wechatpy'])[0]

            shove = Shove(session)
            storage = ShoveStorage(shove, prefix)
            self.session = storage

        self.session.set('access_token', access_token)

    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 _handle_result(self, res, method=None, url=None, **kwargs):
        res.encoding = 'utf-8'
        result = res.json()
        if 'base_resp' in result:
            # Different response in device APIs. Fuck tencent!
            result = result['base_resp']
        if 'errcode' in result:
            result['errcode'] = int(result['errcode'])

        if 'errcode' in result and result['errcode'] != 0:
            errcode = result['errcode']
            errmsg = result['errmsg']
            if errcode in (40001, 40014, 42001):
                # access_token expired, fetch a new one and retry request
                self.fetch_access_token()
                kwargs['params']['access_token'] = self.session.get(
                    'access_token'
                )
                return self._request(
{'fraction_non_alphanumeric': 0.09957061622374376, 'fraction_numerical': 0.005570384124405245, 'mean_word_length': 1.9134550371872887, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4899462', 'n_tokens_mistral': 2458, 'n_tokens_neox': 2383, 'n_words': 551}