def get_payout_item(self, payout_item_id, debug=False):
        request = PayoutsItemGetRequest(payout_item_id)

        try:
            response = self.client.execute(request)

            if debug:
                print("Status Code: ", response.status_code)
                print("Payout Item ID: " + response.result.payout_item_id)
                print("Payout Item Status: " +
                      response.result.transaction_status)
                print("Links: ")
                for link in response.result.links:
                    print('\t{}: {}\tCall Type: {}'.format(
                        link.rel, link.href, link.method))

                # To toggle print the whole body comment/uncomment the below line
                #json_data = self.object_to_json(response.result)
                #print "json_data: ", json.dumps(json_data, indent=4)

            return response
        except HttpError as httpe:
            # Handle server side API failure
            encoder = Encoder([Json()])
            error = encoder.deserialize_response(httpe.message, httpe.headers)
            print("Error: " + error["name"])
            print("Error message: " + error["message"])
            print("Information link: " + error["information_link"])
            print("Debug id: " + error["debug_id"])

        except IOError as ioe:
            #Handle cient side connection failures
            print(ioe.message)
Beispiel #2
0
    def test_Encoder_deserialize_response_text(self):
        j = 'some plain text'
        headers = {"content-type": "text/plain"}

        b = Encoder([Json(), Text(), Multipart(), FormEncoded()]).deserialize_response(j, headers)

        self.assertEqual(j, b)
Beispiel #3
0
    def test_Encoder_deserialize_response_multipart(self):
        j = 'some plain text'
        headers = {"content-type": "multipart/form-data"}

        try:
            b = Encoder([Json(), Text(), Multipart(), FormEncoded()]).deserialize_response(j, headers)
            self.fail('deserialize should have thrown with content-type multipart')
        except IOError as e:
            self.assertTrue('Multipart does not support deserialization', str(e))
Beispiel #4
0
    def test_Encoder_deserialize_response_formEncoded(self):
        data = 'key=value&key_two=value%20with%20spaces'
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}

        try:
            b = Encoder([Json(), Text(), Multipart(), FormEncoded()]).deserialize_response(data, headers)
            self.fail('deserialize should have thrown with content-type formencoded')
        except IOError as e:
            self.assertTrue('FormEncoded does not support deserialization', str(e))
Beispiel #5
0
    def test_Encoder_serialize_request_withTextContentType_stringifiesData(self):
        req = GenericRequest()
        req.body = "some text data"
        req.headers = {
            "content-type": "text/plain; charset=utf8"
        }

        b = Encoder([Json(), Text(), Multipart(), FormEncoded()]).serialize_request(req)
        self.assertEqual(req.body, b)
Beispiel #6
0
    def test_Encoder_deserialize_response_Json(self):
        j = '{"key": "value", "list": ["one", "two"]}'

        headers = {"content-type": "application/json"}

        b = Encoder([Json(), Text(), Multipart(), FormEncoded()]).deserialize_response(j, headers)

        self.assertEqual("value", b["key"])
        self.assertEqual(["one", "two"], b["list"])
Beispiel #7
0
    def test_Encoder_deserialize_response_throwsWhenContentTypeNotSupported(self):
        j = '{"key": "value", "list": ["one", "two"]}'

        headers = {"content-type": "application/xml"}

        try:
            b = Encoder([Json(), Text(), Multipart(), FormEncoded()]).deserialize_response(j, headers)
        except IOError as e:
            self.assertIsInstance(e, IOError)
            self.assertTrue("Unable to deserialize response with content-type application/xml. Supported decodings are " in str(e))
Beispiel #8
0
    def test_Encoder_deserialize_response_throwsWhenHeadersNone(self):
        j = '{"key": "value", "list": ["one", "two"]}'

        headers = None

        try:
            b = Encoder([Json(), Text(), Multipart(), FormEncoded()]).deserialize_response(j, headers)
        except IOError as e:
            self.assertIsInstance(e, IOError)
            self.assertEqual("Http response does not have content-type header set", str(e))
Beispiel #9
0
    def test_Encoder_serialize_request_throwsWhenHeadersNone(self):
        req = GenericRequest()
        req.body = {
            "key": "value",
            "list": ["one", "two"]
        }

        try:
            Encoder([Json(), Text(), Multipart(), FormEncoded()]).serialize_request(req)
        except Exception as e:
            self.assertIsInstance(e, IOError)
            self.assertEqual("Http request does not have content-type header set", str(e))
Beispiel #10
0
    def test_Encode_serialize_request_withFormEncodedContentType_stringifysData(self):
        request = GenericRequest()
        request.path = "/"
        request.verb = "POST"
        request.headers = {"content-type": "application/x-www-form-urlencoded; charset=utf8"}
        request.body = {
            'key': 'value',
            'key_two': 'value with spaces'
        }

        serialized = Encoder([Json(), Text(), Multipart(), FormEncoded()]).serialize_request(request)
        self.assertIsNotNone(re.match('(key=value&key_two=value%20with%20spaces|key_two=value%20with%20spaces&key=value)', serialized))
Beispiel #11
0
    def create_payouts_failure(self, debug=False):
        request = PayoutsPostRequest()
        request.request_body(self.build_request_body(True))

        try:
            response = self.client.execute(request)
        except HttpError as httpe:
            if debug:
                # Handle server side API failure
                encoder = Encoder([Json()])
                error = encoder.deserialize_response(httpe.message, httpe.headers)
                print("Error: " + error["name"])
                print("Error message: " + error["message"])
                print("Information link: " + error["information_link"])
                print("Debug id: " + error["debug_id"])
                print("Details: ")
                for detail in error["details"]:
                    print("Error location: " + detail["location"])
                    print("Error field: " + detail["field"])
                    print("Error issue: " + detail["issue"])

        except IOError as ioe:
            #Handle cient side connection failures
            print(ioe.message)
Beispiel #12
0
    def test_Encoder_serialize_request_withJsonContentType_stringifysData(self):
        req = GenericRequest()
        req.body = {
            "key": "value",
            "list": ["one", "two"]
        }
        req.headers = {
            "content-type": "application/json; charset=utf8"
        }

        j = Encoder([Json(), Text(), Multipart(), FormEncoded()]).serialize_request(req)

        self.assertTrue('{' in j)
        self.assertTrue('"key": "value"' in j)
        self.assertTrue('"list": ["one", "two"]' in j)
Beispiel #13
0
    def test_Encoder_serialize_request_throwsWhenContentTypeNotJson(self):
        req = GenericRequest()
        req.body = {
            "key": "value",
            "list": ["one", "two"]
        }
        req.headers = {
            "Content-Type": "application/xml"
        }

        try:
            Encoder([Json(), Text(), Multipart(), FormEncoded()]).serialize_request(req)
        except Exception as e:
            self.assertIsInstance(e, IOError)
            self.assertTrue("Unable to serialize request with Content-Type application/xml. Supported encodings are " in str(e))
    def add_form_part(self, key, formPart):
        retValue =  "Content-Disposition: form-data; name=\"{}\"".format(key)
        formatted_headers = self.format_headers(formPart.headers)
        if formatted_headers["content-type"] == "application/json":
            retValue += "; filename=\"{}.json\"".format(key)
        retValue += CRLF

        for key in formPart.headers:
            retValue += "{}: {}{}".format(key, formPart.headers[key], CRLF)

        retValue += CRLF

        req = FormPartRequest()
        req.headers = formatted_headers
        req.body = formPart.value
        retValue += Encoder([Json(), Text(), FormEncoded()]).serialize_request(req)

        retValue += CRLF
        return retValue
Beispiel #15
0
    def test_Encoder_serialize_request_withMultipartContentType_stringifysData(self):
        request = GenericRequest()
        request.path = "/"
        request.verb = "POST"
        request.headers = {"content-type": "multipart/form-data; charset=utf8"}
        f = File(abspath('tests/resources/fileupload_test_binary.jpg'))
        data = f.read()

        request.body = {"some_key": "some_value", "some_nested[key]": "some_nested_value", "file": f}

        serialized = Encoder([Json(), Text(), Multipart(), FormEncoded()]).serialize_request(request)
        self.assertTrue("multipart/form-data; boundary=" in request.headers["content-type"])

        self.assertTrue("Content-Disposition: form-data; name=\"some_key\"" in serialized)
        self.assertTrue("some_value" in serialized)
        self.assertTrue("Content-Disposition: form-data; name=\"some_nested[key]\"" in serialized)
        self.assertTrue("some_nested_value" in serialized)
        self.assertTrue("Content-Disposition: form-data; name=\"file\"; filename=\"fileupload_test_binary.jpg\"" in serialized)
        self.assertTrue("Content-Type: image/jpeg" in serialized)
        self.assertTrue(str(data) in serialized)

        f.close()
Beispiel #16
0
    def test_Encoder_serialize_request_withMultipartContentType_encodesFormPart(self):
        request = GenericRequest()
        request.path = "/"
        request.verb = "POST"
        request.headers = {"content-type": "multipart/form-data; charset=utf8"}
        f = File(abspath('tests/resources/fileupload_test_binary.jpg'))
        data = f.read()

        request.body = {
            "file": f,
            "input": FormPart({"key": "val"}, {"Content-Type": "application/json"})
        }

        serialized = Encoder([Json(), Text(), Multipart(), FormEncoded()]).serialize_request(request)
        self.assertTrue("multipart/form-data; boundary=" in request.headers["content-type"])

        self.assertTrue("Content-Disposition: form-data; name=\"input\"; filename=\"input.json\"" in serialized)
        self.assertTrue("{\"key\": \"val\"}" in serialized)
        self.assertTrue("Content-Disposition: form-data; name=\"file\"; filename=\"fileupload_test_binary.jpg\"" in serialized)
        self.assertTrue("Content-Type: image/jpeg" in serialized)
        self.assertTrue(str(data) in serialized)
        self.assertIsNotNone(re.search('.*input.json.*fileupload_test_binary.jpg.*', serialized, re.MULTILINE | re.DOTALL))

        f.close()
Beispiel #17
0
 def __init__(self, environment):
     self._injectors = []
     self.environment = environment
     self.encoder = Encoder([Json(), Text(), Multipart(), FormEncoded()])
Beispiel #18
0
class HttpClient(object):
    def __init__(self, environment):
        self._injectors = []
        self.environment = environment
        self.encoder = Encoder([Json(), Text(), Multipart(), FormEncoded()])

    def get_user_agent(self):
        return "Python HTTP/1.1"

    def get_timeout(self):
        return 30

    def add_injector(self, injector):
        if injector and '__call__' in dir(injector):
            self._injectors.append(injector)
        else:
            message = "injector must be a function or implement the __call__ method"
            print(message)
            raise TypeError(message)

    def execute(self, request):
        reqCpy = copy.deepcopy(request)

        try:
            getattr(reqCpy, 'headers')
        except AttributeError:
            reqCpy.headers = {}

        for injector in self._injectors:
            injector(reqCpy)

        data = None

        formatted_headers = self.format_headers(reqCpy.headers)

        if "user-agent" not in formatted_headers:
            reqCpy.headers["user-agent"] = self.get_user_agent()

        if hasattr(reqCpy, 'body') and reqCpy.body is not None:
            raw_headers = reqCpy.headers
            reqCpy.headers = formatted_headers
            data = self.encoder.serialize_request(reqCpy)
            reqCpy.headers = self.map_headers(raw_headers, formatted_headers)

        resp = requests.request(method=reqCpy.verb,
                                url=self.environment.base_url + reqCpy.path,
                                headers=reqCpy.headers,
                                data=data)

        return self.parse_response(resp)

    def format_headers(self, headers):
        return dict((k.lower(), v) for k, v in headers.items())

    def map_headers(self, raw_headers, formatted_headers):
        for header_name in raw_headers:
            if header_name.lower() in formatted_headers:
                raw_headers[header_name] = formatted_headers[
                    header_name.lower()]
        return raw_headers

    def parse_response(self, response):
        status_code = response.status_code

        if 200 <= status_code <= 299:
            body = ""
            if response.text and (len(response.text) > 0
                                  and response.text != 'None'):
                body = self.encoder.deserialize_response(
                    response.text, self.format_headers(response.headers))

            return HttpResponse(body, response.status_code, response.headers)
        else:
            raise HttpError(response.text, response.status_code,
                            response.headers)