Пример #1
0
    def send_request(self,
                     method,
                     path,
                     params,
                     body,
                     verbose=False,
                     print_json=False):
        """
        REST Transaction
        """

        buf = StringIO()
        out = lambda s: buf.write(s + '\n')
        nl = lambda: buf.write('\n')
        body_json = None

        print('{}: {}'.format(method, path))
        if params:
            path = "{}?{}".format(path, params)
            if verbose:
                print(dict2yaml(params))
                print('')
        if body:
            body_json = json.dumps(body)
            if verbose:
                print(dict2yaml(body))
                print('')

        if verbose:
            buf.write('- - - Request - - -\n')
            buf.write('{} {}\n'.format(method, path))
            if body:
                nl()
                out(str(dict2yaml(body)))
        try:
            response = res_body = None

            response, _res_body = self.conn.request(self.url + path, method,
                                                    body_json, self.headers)
            res_body = _res_body.decode('ascii')

            length = None
            encoding = None
            if 'content-length' in response:
                length = response['content-length']
            if 'transfer-encoding' in response:
                encoding = response['transfer-encoding']

            if verbose:
                out('- - - Response - - -')
                out('status: {}'.format(response.status))
                out('reason: {}'.format(response.reason))
                if length:
                    out('content-length: {}'.format(length))
                if encoding:
                    out('transfer-encoding: {}'.format(encoding))
                nl()
            else:
                if not response['status'].startswith('2'):  # 2XX
                    out('[Error] status: {}, reason: {}'.format(
                        response.status, response.reason))

            # TODO: REST API responses should include Content-Type
            if length or encoding == 'chunked':
                if res_body.startswith('{') or res_body.startswith(
                        '['):  # Must be application/json
                    if length and int(length) > 1 or encoding == 'chunked':
                        if print_json:
                            #out(str(res_body))
                            out(pprint.pformat(json_loads(res_body)))
                        else:  # YAML
                            out(str(dict2yaml(json_loads(res_body))))
                else:  # Must be text/plain
                    if int(length) > 0:
                        out(res_body)
                        res_body = '{}'  # for json.loads
                    else:
                        res_body = '{}'  # for json.loads
            else:
                res_body = '{}'

            buf.seek(0)
            output = buf.read()
            buf.close()
            return (response, json_loads(res_body), output)
        except Exception:
            traceback.print_exc()
            print('[Error] REST transaction failure')
            print('[Hint] check if the target REST server is running')
            print('[Hint] you might need to unset http_proxy')
            sys.exit(1)
Пример #2
0
    def send_request(self, method, path, params, body, verbose=False, print_json=False):
        """
        REST Transaction
        """
        
        buf = StringIO()
        out = lambda s: buf.write(s+'\n')
        nl = lambda: buf.write('\n') 
        body_json = None
        
        print('{}: {}'.format(method, path))
        if params:
            path = "{}?{}".format(path, params)
            if verbose:
                print(dict2yaml(params))
                print('')
        if body:
            body_json = json.dumps(body)
            if verbose:
                print(dict2yaml(body))
                print('')

        if verbose:
            buf.write('- - - Request - - -\n')
            buf.write('{} {}\n'.format(method, path))
            if body:
                nl()
                out(str(dict2yaml(body)))
        try:
            response = res_body = None

            response, _res_body = self.conn.request(self.url+path, method, body_json, self.headers) 
            res_body = _res_body.decode('ascii')

            length = None 
            encoding = None
            if 'content-length' in response:
                length = response['content-length']
            if 'transfer-encoding' in response:
                encoding = response['transfer-encoding']
                
            if verbose:
                out('- - - Response - - -')
                out('status: {}'.format(response.status))
                out('reason: {}'.format(response.reason))
                if length:
                    out('content-length: {}'.format(length))
                if encoding:
                    out('transfer-encoding: {}'.format(encoding))
                nl()
            else:
                if not response['status'].startswith('2'):  # 2XX
                    out('[Error] status: {}, reason: {}'.format(response.status, response.reason))

            # TODO: REST API responses should include Content-Type
            if length or encoding == 'chunked':
                if res_body.startswith('{') or res_body.startswith('['):  # Must be application/json
                    if length and int(length) > 1 or encoding == 'chunked':
                        if print_json:
                            #out(str(res_body))
                            out(pprint.pformat(json_loads(res_body)))
                        else:  # YAML
                            out(str(dict2yaml(json_loads(res_body))))
                else:  # Must be text/plain
                    if int(length) > 0:
                        out(res_body)
                        res_body = '{}'  # for json.loads
                    else:
                        res_body = '{}'  # for json.loads
            else:
                res_body = '{}'

            buf.seek(0)
            output = buf.read()
            buf.close()
            return (response, json_loads(res_body), output)
        except Exception:
            traceback.print_exc()
            print('[Error] REST transaction failure')
            print('[Hint] check if the target REST server is running')
            print('[Hint] you might need to unset http_proxy')
            sys.exit(1)
Пример #3
0
def _transform_print(x):
    print(dict2yaml(x))
Пример #4
0
def _transform_print(x):
    print(dict2yaml(x))