Wrapper around botocore's base client API call method.
487135
def xray_botocore_api_call(wrapped, instance, args, kwargs):
    """"""
    return generic_xray_wrapper(
        wrapped, instance, args, kwargs,
        name=get_service_name,
        namespace='aws',
        metadata_extractor=extract_aws_metadata,
        error_handling_type=ERROR_HANDLING_BOTOCORE,
    )
1245412
def callRemote(self, *a, **kw):
        
        if not self.running:
            return defer.fail(ServiceStopped())
        return self.clientFactory.callRemote(*a, **kw)
62393
def invoke(stage, async, dry_run, config_file, args):
    """"""
    config = _load_config(config_file)
    if stage is None:
        stage = config['devstage']

    cfn = boto3.client('cloudformation')
    lmb = boto3.client('lambda')

    try:
        stack = cfn.describe_stacks(StackName=config['name'])['Stacks'][0]
    except botocore.exceptions.ClientError:
        raise RuntimeError('This project has not been deployed yet.')
    function = _get_from_stack(stack, 'Output', 'FunctionArn')

    if dry_run:
        invocation_type = 'DryRun'
    elif async:
        invocation_type = 'Event'
    else:
        invocation_type = 'RequestResponse'

    # parse input arguments
    data = {}
    for arg in args:
        s = arg.split('=', 1)
        if len(s) != 2:
            raise ValueError('Invalid argument ' + arg)
        if s[0][-1] == ':':
            # JSON argument
            data[s[0][:-1]] = json.loads(s[1])
        else:
            # string argument
            data[s[0]] = s[1]

    rv = lmb.invoke(FunctionName=function, InvocationType=invocation_type,
                    Qualifier=stage,
                    Payload=json.dumps({'kwargs': data}, sort_keys=True))
    if rv['StatusCode'] != 200 and rv['StatusCode'] != 202:
        raise RuntimeError('Unexpected error. Status code = {}.'.format(
            rv['StatusCode']))
    if invocation_type == 'RequestResponse':
        payload = json.loads(rv['Payload'].read().decode('utf-8'))
        if 'FunctionError' in rv:
            if 'stackTrace' in payload:
                print('Traceback (most recent call last):')
                for frame in payload['stackTrace']:
                    print('  File "{}", line {}, in {}'.format(
                        frame[0], frame[1], frame[2]))
                    print('    ' + frame[3])
                print('{}: {}'.format(payload['errorType'],
                                      payload['errorMessage']))
            else:
                raise RuntimeError('Unknown error')
        else:
            print(str(payload))
520448
def openAPIDoc(**kwargs):
    
    s = yaml.dump(kwargs, default_flow_style=False)
    def deco(routeHandler):
        # Wrap routeHandler, retaining name and __doc__, then edit __doc__.

        # The only reason we need to do this is so we can be certain
        # that __doc__ will be modifiable. partial() objects have
        # a modifiable __doc__, but native function objects do not.
        ret = functools.wraps(routeHandler)(routeHandler)
        if not ret.__doc__:
            ret.__doc__ = ''
        ret.__doc__ = cleandoc(ret.__doc__) + '\n---\n' + s
        return ret
    return deco
548907
def _api_handler(self, *args, **kwargs):
        
        keyword_arguments = {}
        keyword_arguments.update(self.keywords)
        keyword_arguments.update(kwargs)
        return api_handler(*args, **keyword_arguments)
248681
def call(method, *args, **kwargs):
    '''
    
    '''
    kwargs = clean_kwargs(**kwargs)
    return getattr(pyeapi_device['connection'], method)(*args, **kwargs)
194918
async def batch_call_api(container, apis, timeout = 120.0):
    
    apiHandles = [(object(), api) for api in apis]
    apiEvents = [ModuleAPICall(handle, targetname, name, params = params)
                 for handle, (targetname, name, params) in apiHandles]
    apiMatchers = tuple(ModuleAPIReply.createMatcher(handle) for handle, _ in apiHandles)
    async def process():
        for e in apiEvents:
            await container.wait_for_send(e)
    container.subroutine(process(), False)
    eventdict = {}
    async def process2():
        ms = len(apiMatchers)
        matchers = Diff_(apiMatchers)
        while ms:
            ev, m = await matchers
            matchers = Diff_(matchers, remove=(m,))
            eventdict[ev.handle] = ev
    await container.execute_with_timeout(timeout, process2())
    for e in apiEvents:
        if e.handle not in eventdict:
            e.canignore = True
            container.scheduler.ignore(ModuleAPICall.createMatcher(e.handle))
    return [eventdict.get(handle, None) for handle, _ in apiHandles]
481051
def api(func):
    """"""
    @wraps(func)
    def decorated_function(*args, **kwargs):
        try:
            value = func(*args, **kwargs)
        except BaseException as e:
            value = {
                "status": "failed",
                "error": "Unkonwn error!"
            }
            flask.current_app.logger.error("Unkonwn error: %s" % str(e))
            flask.current_app.logger.exception(e)

        status = 200
        mimetype = 'application/json'
        content = json.dumps(value)
        callback = flask.request.args.get('callback', False)
        if callback:
            content = str(callback) + '(' + content + ')'
            mimetype = 'application/javascript'

        return flask.current_app.response_class(content, status=status, mimetype=mimetype)
    return decorated_function
1044611
def make_call_with_cb(self, fun, *args):
        """"""

        cid, event = self.handler.register_callback()
        argscp = list(args)
        argscp.append(cid)
        self.make_call(fun, *argscp)
        return event
337617
def create_async_api_call_func(api, verb):
    

    # Scopes some local context in which we can build
    # request functions with reflection that primed with
    # some static parameters.
    def api_call_func(self, **kwargs):

        def _async_call_handler():
            api_method = getattr(self, api_method_name(verb, api))
            return api_method(**kwargs)

        return self._executor.submit(_async_call_handler)

    method_name = async_api_method_name(verb, api)

    api_call_func.__name__ = method_name
    api_call_func.__doc__ = "{}\nParameters:\n  {}".format(
        method_name, '\n  '.join(api.request_classes[verb]().keys()))

    return api_call_func
801637
def cli(context, verbose, api_key, base_url, workers):
    ''''''

    configure_logging(verbose)

    client_params.clear()
    client_params['api_key'] = api_key
    client_params['workers'] = workers
    if base_url:
        client_params['base_url'] = base_url
1343639
def rpc_call(self, request, method=None, **payload):
        
        if not method or self.separator not in method:
            raise AssertionError("Wrong method name: {0}".format(method))

        resource_name, method = method.split(self.separator, 1)
        if resource_name not in self.api.resources:
            raise AssertionError("Unknown method " + method)

        data = QueryDict('', mutable=True)
        data.update(payload.get('data', dict()))
        data['callback'] = payload.get('callback') or request.GET.get(
            'callback') or request.GET.get('jsonp') or 'callback'
        for h, v in payload.get('headers', dict()).iteritems():
            request.META["HTTP_%s" % h.upper().replace('-', '_')] = v

        request.POST = request.PUT = request.GET = data
        delattr(request, '_request')
        request.method = method.upper()
        request.META['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
        params = payload.pop('params', dict())
        response = self.api.call(resource_name, request, **params)

        if not isinstance(response, SerializedHttpResponse):
            return response

        if response['Content-type'] in self._meta.emitters_dict:
            return HttpResponse(response.content, status=response.status_code)

        if response.status_code == 200:
            return response.response

        raise AssertionError(response.response)
149059
def callm(method, param_dict, POST=False, socket_timeout=None, data=None):
    
    try:
        param_dict['api_key'] = config.ECHO_NEST_API_KEY
        param_list = []
        if not socket_timeout:
            socket_timeout = config.CALL_TIMEOUT

        for key,val in param_dict.iteritems():
            if isinstance(val, list):
                param_list.extend( [(key,subval) for subval in val] )
            elif val is not None:
                if isinstance(val, unicode):
                    val = val.encode('utf-8')
                param_list.append( (key,val) )

        params = urllib.urlencode(param_list)

        orig_timeout = socket.getdefaulttimeout()
        socket.setdefaulttimeout(socket_timeout)

        if(POST):
            if (not method == 'track/upload') or ((method == 'track/upload') and 'url' in param_dict):
                """
                this is a normal POST call
                """
                url = 'http://%s/%s/%s/%s' % (config.API_HOST, config.API_SELECTOR,
                                            config.API_VERSION, method)

                if data is None:
                    data = ''
                data = urllib.urlencode(data)
                data = "&".join([data, params])

                f = opener.open(url, data=data)
            else:
                """
                upload with a local file is special, as the body of the request is the content of the file,
                and the other parameters stay on the URL
                """
                url = '/%s/%s/%s?%s' % (config.API_SELECTOR, config.API_VERSION,
                                            method, params)

                if ':' in config.API_HOST:
                    host, port = config.API_HOST.split(':')
                else:
                    host = config.API_HOST
                    port = 80

                if config.TRACE_API_CALLS:
                    logger.info("%s/%s" % (host+':'+str(port), url,))
                conn = httplib.HTTPConnection(host, port = port)
                conn.request('POST', url, body = data, headers = dict([('Content-Type', 'application/octet-stream')]+headers))
                f = conn.getresponse()

        else:
            """
            just a normal GET call
            """
            url = 'http://%s/%s/%s/%s?%s' % (config.API_HOST, config.API_SELECTOR, config.API_VERSION,
                                            method, params)

            f = opener.open(url)

        socket.setdefaulttimeout(orig_timeout)

        # try/except
        response_dict = get_successful_response(f)
        return response_dict

    except IOError, e:
        if hasattr(e, 'reason'):
            raise EchoNestIOError(error=e.reason)
        elif hasattr(e, 'code'):
            raise EchoNestIOError(code=e.code)
        else:
            raise
201697
def call_and_wrap(func, *args, **kw):
    '''
    '''
    try:
        return func(*args, **kw)
    except api.exceptions.APIException as ex:
        click_exception(ex)
    except urllib3exc.SSLError:
        # see monkey patch above re InsecurePlatformWarning
        if _insecure_warning:
            click.echo(click.style(str(_insecure_warning[0]), fg='red'))
        raise
484549
def update_api_endpoint():
    """"""
    environment = subprocess.check_output(['pipenv',
                                           'run',
                                           'runway',
                                           'whichenv']).decode().strip()
    environment_file = os.path.join(
        os.path.dirname(os.path.realpath(__file__)),
        'src',
        'environments',
        'environment.prod.ts' if environment == 'prod' else 'environment.ts'
    )
    cloudformation = boto3.resource('cloudformation')
    stack = cloudformation.Stack(STACK_PREFIX + environment)
    endpoint = [i['OutputValue'] for i in stack.outputs
                if i['OutputKey'] == 'ServiceEndpoint'][0]

    with open(environment_file, 'r') as stream:
        content = stream.read()
    content = re.sub(r'api_url: \'.*\'$',
                     "api_url: '%s/api'" % endpoint,
                     content,
                     flags=re.M)
    with open(environment_file, 'w') as stream:
        stream.write(content)
1337305
def method_caller(method_name, *args, **kwargs):
	
	def call_method(target):
		func = getattr(target, method_name)
		return func(*args, **kwargs)
	return call_method
982614
def _dispatcher(self, connection, event):
        
        super(BaseBot, self)._dispatcher(connection, event)
        for handler in self.events[event.eventtype()]:
            handler(self, connection, event)