Exemple #1
0
    def __request(self, method, endpoint, data):
        """ Do requests """
        url = self.__get_url(endpoint)
        auth = None
        params = {}
        headers = {
            "user-agent": "WooCommerce API Client-Python/%s" % __version__,
            "accept": "application/json"
        }

        if self.is_ssl is True and self.query_string_auth is False:
            auth = (self.consumer_key, self.consumer_secret)
        elif self.is_ssl is True and self.query_string_auth is True:
            params = {
                "consumer_key": self.consumer_key,
                "consumer_secret": self.consumer_secret
            }
        else:
            url = self.__get_oauth_url(url, method)

        if data is not None:
            data = jsonencode(data, ensure_ascii=False)
            headers["content-type"] = "application/json"

        return request(method=method,
                       url=url,
                       verify=self.verify_ssl,
                       auth=auth,
                       params=params,
                       data=data,
                       timeout=self.timeout,
                       headers=headers)
Exemple #2
0
    def __request(self, method, endpoint, data):
        """ Do requests """
        url = self.__get_url(endpoint)
        auth = None
        headers = {
            "user-agent": "WooCommerce API Client-Python/%s" % __version__,
            "content-type": "application/json;charset=utf-8",
            "accept": "application/json"
        }

        if self.is_ssl is True:
            auth = (self.consumer_key, self.consumer_secret)
        else:
            url = self.__get_oauth_url(url, method)

        if data is not None:
            data = jsonencode(data, ensure_ascii=False).encode('utf-8')

        return request(
            method=method,
            url=url,
            verify=self.verify_ssl,
            auth=auth,
            data=data,
            timeout=self.timeout,
            headers=headers
        )
Exemple #3
0
    def __request(self, method, endpoint, data, params={}, **kwargs):
        url = self.__get_url(endpoint)

        if data is not None:
            data = jsonencode(data)

        headers = self.__get_headers()

        if "headers" in kwargs:
            headers.update(kwargs.get("headers", {}))
            del kwargs["headers"]

        return self.session.send(
            self.session.prepare_request(
                Request(
                    method=method,
                    url=url,
                    auth=None,
                    params=params,
                    data=data,
                    headers=headers,
                    **kwargs
                )
            )
        )
Exemple #4
0
    def __request(self, method, endpoint, data, **kwargs):
        """ Do requests """

        endpoint_url = self.requester.endpoint_url(endpoint)
        endpoint_url = self.auth.get_auth_url(endpoint_url, method, **kwargs)
        auth = self.auth.get_auth()

        content_type = kwargs.get('headers', {}).get('content-type', 'application/json')

        if data is not None and content_type.startswith('application/json'):
            data = jsonencode(data, ensure_ascii=False)
            # enforce utf-8 encoded binary
            if isinstance(data, binary_type):
                try:
                    data = data.decode('utf-8')
                except UnicodeDecodeError:
                    data = data.decode('latin-1')
            if isinstance(data, text_type):
                data = data.encode('utf-8')


        response = self.requester.request(
            method=method,
            url=endpoint_url,
            auth=auth,
            data=data,
            **kwargs
        )

        if response.status_code not in [200, 201, 202]:
            self.request_post_mortem(response)

        return response
Exemple #5
0
    def __request(self, method, endpoint, data):
        """ Do requests """
        url = self.__get_url(endpoint)
        auth = None
        headers = {
            "user-agent": "WooCommerce API Client-Python/%s" % __version__,
            "content-type": "application/json;charset=utf-8",
            "accept": "application/json"
        }

        if self.is_ssl is True:
            auth = (self.consumer_key, self.consumer_secret)
        else:
            url = self.__get_oauth_url(url, method)

        if data is not None:
            data = jsonencode(data, ensure_ascii=False).encode('utf-8')

        return request(method=method,
                       url=url,
                       verify=self.verify_ssl,
                       auth=auth,
                       data=data,
                       timeout=self.timeout,
                       headers=headers)
Exemple #6
0
    def __request(self, method, endpoint, data, extra_params=None):
        """ Do requests """
        url = self.__get_url(endpoint)
        auth = None
        params = {}
        headers = {
            "user-agent": "WooCommerce API Client-Python/%s" % __version__,
            "content-type": "application/json;charset=utf-8",
            "accept": "application/json"
        }

        if self.is_ssl is True and self.query_string_auth is False:
            auth = (self.consumer_key, self.consumer_secret)
        elif self.is_ssl is True and self.query_string_auth is True:
            params = {
                "consumer_key": self.consumer_key,
                "consumer_secret": self.consumer_secret
            }
        else:
            url = self.__get_oauth_url(url, method)

        if data:
            data = jsonencode(data, ensure_ascii=False).encode('utf-8')
        if extra_params:
            for key, value in extra_params.items():
                params[key] = value

        return request(method=method,
                       url=url,
                       verify=self.verify_ssl,
                       auth=auth,
                       params=params,
                       data=data,
                       timeout=self.timeout,
                       headers=headers)
Exemple #7
0
    async def __request(self, method, endpoint, data, params=None, **kwargs):
        """ Do requests """
        if params is None:
            params = {}
        url = self.__get_url(endpoint)
        auth = None
        headers = {
            "user-agent": "WooCommerce API Client-Python/%s" % __version__,
            "accept": "application/json"
        }

        if self.is_ssl is True and self.query_string_auth is False:
            # change to aiohttp.BasicAuth
            # auth = (self.consumer_key, self.consumer_secret)
            auth = aiohttp.BasicAuth(self.consumer_key, self.consumer_secret)
        elif self.is_ssl is True and self.query_string_auth is True:
            params.update({
                "consumer_key": self.consumer_key,
                "consumer_secret": self.consumer_secret
            })
        else:
            encoded_params = urlencode(params)
            url = "%s?%s" % (url, encoded_params)
            url = self.__get_oauth_url(url, method, **kwargs)

        if data is not None:
            data = jsonencode(data, ensure_ascii=False).encode('utf-8')
            headers["content-type"] = "application/json;charset=utf-8"

        # Change to async
        # return request(
        #     method=method,
        #     url=url,
        #     verify=self.verify_ssl,
        #     auth=auth,
        #     params=params,
        #     data=data,
        #     timeout=self.timeout,
        #     headers=headers,
        #     **kwargs
        # )
        async with aiohttp.ClientSession() as session:
            async with await session.request(method=method,
                                             url=url,
                                             verify_ssl=self.verify_ssl,
                                             auth=auth,
                                             params=params,
                                             data=data,
                                             timeout=self.timeout,
                                             headers=headers,
                                             **kwargs) as resp:
                json = await resp.json()
                status_code = resp.status
        # print(text)
        return Response(status_code, json)
Exemple #8
0
def request(method, action, param=None, **params):
    """
        发送请求数据
    """
    if param:
        params.update(param)

    params = dict((k, params[k]) for k in params if params[k] is not None)
    info("%s/%s : %s", API.SITE, action, params)
    if Config.PROXY:
        conn = HTTPSConnection(Config.PROXY)
        conn.set_tunnel(API.SITE, 443)
    else:
        conn = HTTPSConnection(API.SITE)

    if method in ['PUT', 'POST', 'PATCH']:
        # 从public_v(4,6)获取的IP是bytes类型,在json.dumps时会报TypeError
        params['content'] = str(params.get('content'))
        params = jsonencode(params)
    else:  # (GET, DELETE) where DELETE doesn't require params in Cloudflare
        if params:
            action += '?' + urlencode(params)
        params = None
    if not Config.ID:
        headers = {
            "Content-type": "application/json",
            "Authorization": "Bearer " + Config.TOKEN
        }
    else:
        headers = {
            "Content-type": "application/json",
            "X-Auth-Email": Config.ID,
            "X-Auth-Key": Config.TOKEN
        }
    conn.request(method, '/client/v4/zones' + action, params, headers)
    response = conn.getresponse()
    res = response.read().decode('utf8')
    conn.close()
    if response.status < 200 or response.status >= 300:
        warning('%s : error[%d]:%s', action, response.status, res)
        raise Exception(res)
    else:
        data = jsondecode(res)
        debug('%s : result:%s', action, data)
        if not data:
            raise Exception("Empty Response")
        elif data.get('success'):
            return data.get('result', [{}])
        else:
            raise Exception(data.get('errors', [{}]))
Exemple #9
0
    async def request(self, method, endpoint, data, ignore_headers=False):
        """ Do requests """
        url = self.__get_url(endpoint)
        auth = None
        params = {}

        if ignore_headers:
            # It was discovered in https://github.com/channable/issues/issues/1929 that not sending
            # the 'content-type' and 'accept' headers will solve an issue where the api returns an
            # invalid json response beginning with `Order:<br/>{}`
            headers = {
                "user-agent":
                "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
            }
        else:
            headers = {
                "user-agent":
                "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36",
                "content-type": "application/json;charset=utf-8",
                "accept": "application/json"
            }

        if self.is_ssl is True and self.query_string_auth is False:
            auth = aiohttp.BasicAuth(self.consumer_key, self.consumer_secret)
        elif self.is_ssl is True and self.query_string_auth is True:
            params = {
                "consumer_key": self.consumer_key,
                "consumer_secret": self.consumer_secret
            }
        else:
            url = self.__get_oauth_url(url, method)

        if data is not None:
            data = jsonencode(data, ensure_ascii=False).encode('utf-8')

        return await self.client_session.request(
            method=method,
            url=url,
            #verify=self.verify_ssl,
            auth=auth,
            params=params,
            data=data,
            #timeout=self.timeout,
            headers=headers)
Exemple #10
0
def request(method, action, param=None, **params):
    """
        发送请求数据
    """
    if param:
        params.update(param)

    info("$s %s : params:%s", action, params)
    if PROXY:
        conn = HTTPSConnection(PROXY)
        conn.set_tunnel(API_SITE, 443)
    else:
        conn = HTTPSConnection(API_SITE)

    if method in ['PUT', 'POST', 'PATCH']:
        # 从public_v(4,6)获取的IP是bytes类型,在json.dumps时会报TypeError
        params['content'] = str(params.get('content'))
        params = jsonencode(params)
    else:  # (GET, DELETE) where DELETE doesn't require params in Cloudflare
        if params:
            action += '?' + urlencode(params)
        params = None
    conn.request(
        method, '/client/v4/zones' + action, params, {
            "Content-type": "application/json",
            "X-Auth-Email": ID,
            "X-Auth-Key": TOKEN
        })
    response = conn.getresponse()
    res = response.read()
    conn.close()
    if response.status < 200 or response.status >= 300:
        raise Exception(res)
    else:
        data = jsondecode(res.decode('utf8'))
        debug('%s : result:%s', action, data)
        if not data:
            raise Exception("Empty Response")
        elif data.get('success'):
            return data.get('result', [{}])
        else:
            raise Exception(data.get('errors', [{}]))
Exemple #11
0
    def __request(self, method, endpoint, data):
        """ Do requests """
        url = self.__get_url(endpoint)
        auth = None
        params = {}
        headers = {
            "user-agent": "WooCommerce API Client-Python/%s" % __version__,
            "accept": "application/json"
        }

        if self.is_ssl is True and self.query_string_auth is False:
            auth = (self.consumer_key, self.consumer_secret)
        elif self.is_ssl is True and self.query_string_auth is True:
            params = {
                "consumer_key": self.consumer_key,
                "consumer_secret": self.consumer_secret
            }
        else:
            url = self.__get_oauth_url(url, method)

        if data is not None:
            data = jsonencode(data, ensure_ascii=False).encode('utf-8')
            headers["content-type"] = "application/json;charset=utf-8"

        req_time = datetime.now().strftime("%d/%m/%Y %H:%M:%S.%f")
        res = request(method=method,
                      url=url,
                      verify=self.verify_ssl,
                      auth=auth,
                      params=params,
                      data=data,
                      timeout=self.timeout,
                      headers=headers)
        res_time = datetime.now().strftime("%d/%m/%Y %H:%M:%S.%f")
        try:
            odoo.http.request.env['woo.req.history.ept'].req_res_data(
                method, url, self.verify_ssl, auth, params, data, self.timeout,
                headers, res, req_time, res_time)
        except Exception as e:
            pass
        return res
Exemple #12
0
    def __request(self, method, endpoint, data, params=None, **kwargs):
        """ Do requests """
        if params is None:
            params = {}
        url = self.__get_url(endpoint)
        auth = None
        headers = {
            "user-agent": "WooCommerce API Client-Python/%s" % __version__,
            "accept": "application/json"
        }
        new_headers = kwargs.pop("headers", {})
        headers.update(new_headers)

        if self.is_ssl is True and self.query_string_auth is False:
            auth = (self.consumer_key, self.consumer_secret)
        elif self.is_ssl is True and self.query_string_auth is True:
            params.update({
                "consumer_key": self.consumer_key,
                "consumer_secret": self.consumer_secret
            })
        else:
            encoded_params = urlencode(params)
            url = "%s?%s" % (url, encoded_params)
            url = self.__get_oauth_url(url, method, **kwargs)

        if data is not None:
            data = jsonencode(data, ensure_ascii=False).encode('utf-8')
            headers["content-type"] = "application/json;charset=utf-8"

        return request(method=method,
                       url=url,
                       verify=self.verify_ssl,
                       auth=auth,
                       params=params,
                       data=data,
                       timeout=self.timeout,
                       headers=headers,
                       **kwargs)
Exemple #13
0
    def __request(self, method, endpoint, data, params=None, **kwargs):
        """ Do requests """
        if params is None:
            params = {}
        url = self.__get_url(endpoint)
        auth = None
        headers = {
            "user-agent": self.userAgent,
            "accept": "application/json"
        }

        if self.is_ssl is True and self.query_string_auth is False:
            auth = HTTPBasicAuth(self.consumer_key, self.consumer_secret)
        elif self.is_ssl is True and self.query_string_auth is True:
            params.update({
                "consumer_key": self.consumer_key,
                "consumer_secret": self.consumer_secret
            })
        else:
            encoded_params = urlencode(params)
            url = f"{url}?{encoded_params}"
            url = self.__get_oauth_url(url, method, **kwargs)

        if data is not None:
            data = jsonencode(data, ensure_ascii=False).encode('utf-8')
            headers["content-type"] = "application/json;charset=utf-8"

        return request(
            method=method,
            url=url,
            verify=self.verify_ssl,
            auth=auth,
            params=params,
            data=data,
            timeout=self.timeout,
            headers=headers,
            **kwargs
        )
Exemple #14
0
    def __request(self, method, endpoint, data, **kwargs):
        """ Do requests """

        endpoint_url = self.requester.endpoint_url(endpoint)
        endpoint_url = self.auth.get_auth_url(endpoint_url, method, **kwargs)
        auth = self.auth.get_auth()

        content_type = kwargs.get('headers', {}).get('content-type',
                                                     'application/json')

        if data is not None and content_type.startswith('application/json'):
            data = jsonencode(data, ensure_ascii=False).encode('utf-8')

        response = self.requester.request(method=method,
                                          url=endpoint_url,
                                          auth=auth,
                                          data=data,
                                          **kwargs)

        if response.status_code not in [200, 201, 202]:
            self.request_post_mortem(response)

        return response
Exemple #15
0
    def __request(self, method, endpoint, data, params=None, **kwargs):
        """ Do requests """
        if params is None:
            params = {}
        url = self.__get_url(endpoint)

        headers = {
            "user-agent": "Github API Client-Python/%s" % __version__,
            "accept": "application/vnd.github.machine-man-preview+json",
            "Authorization": self.token
        }

        if data is not None:
            data = jsonencode(data, ensure_ascii=False).encode('utf-8')
            headers["content-type"] = "application/json;charset=utf-8"

        return request(method=method,
                       url=url,
                       params=params,
                       data=data,
                       timeout=self.timeout,
                       headers=headers,
                       **kwargs)