Executes the API call within the given block. Usage looks like:

     client = StripeClient.new
     charge, resp = client.request { Charge.create }
505878
def request
      @last_response = nil
      old_stripe_client = Thread.current[:stripe_client]
      Thread.current[:stripe_client] = self

      begin
        res = yield
        [res, @last_response]
      ensure
        Thread.current[:stripe_client] = old_stripe_client
      end
    end
149383
public function onChargeCreate(StripeChargeCreateEvent $event, $eventName, EventDispatcherInterface $dispatcher)
    {
        $localCharge = $event->getLocalCharge();

        $result = $this->getStripeManager()->createCharge($localCharge);

        // Check if something went wrong
        if (false === $result) {
            // Stop progation
            $event->setStopReason($this->getStripeManager()->getError())->stopPropagation();

            // Dispatch a failed event
            $dispatcher->dispatch(StripeChargeCreateEvent::FAILED, $event);

            // exit
            return;
        }

        $dispatcher->dispatch(StripeChargeCreateEvent::CREATED, $event);
    }
76582
def perform_create(self, serializer):
        
        if serializer.instance is None:
            serializer.save(user=self.request.user)
40869
@Override
  public void execute() throws Exception {
    ApiClient apiClient = new ApiClient(ApiClient.getToken(), false);
    int rateRemain = apiClient.getRateLimitRemain();
    System.out.println("Your Github API token is valid.");
    System.out.println(rateRemain+ " requests remaining.");
  }
1049029
def _do_api_call(self, call_type=u'', id = None):
        
        endpoint = None
        url = None
        # print "call_type %s" % (call_type)
        if call_type == u'load':
            endpoint = self.get_endpoint("self")
            if id is None:
                raise APIException("LOAD_IDNOTSET", "could not load object")
        elif call_type == u'delete' or (call_type == u"destroy"):
            endpoint = self.get_endpoint("destroy")
            if id is None:
                raise APIException("DELETE_IDNOTSET", "could not delete object")
        elif call_type == u'update':
            endpoint = self.get_endpoint("update")
            if id is None:
                raise APIException("UPDATE_IDNOTSET", "could not load object")
        elif call_type == u'create':
            endpoint = self.get_endpoint("create")
            url = u"%s%s%s" % (self.__api__.base_url, API_BASE_PATH, endpoint['href'])
            # post?
        elif call_type == u'schema':
            # add schema gethering functionality 
            # hackisch
            endpoint = self.get_endpoint("create")
            url = u"%s%s%s/schema" % (self.__api__.base_url, API_BASE_PATH, endpoint['href'])
            endpoint['method'] = u'GET'    
        if id is not None:
            url = u"%s%s%s" % (self.__api__.base_url, API_BASE_PATH, endpoint['href'].replace(u"{id}",id))
        ## excecute the api request
        payload = self.to_json()
        if u'method' in endpoint.keys():
            method = endpoint['method']
        else:
            method = u'GET'
        # request raises exceptions if something goes wrong
        obj = None
        try:
            # dbg
            msg = u"url: %s method:%s p: %s" % (url, method, payload)
            #print msg
            response = self.__api__.request(url, method, data=payload)
            #load update create success
            if ((response.status_code == 200 and 
                 call_type in ['load', 'update']) or
            (response.status_code == 201 and call_type == 'create')):
                msg = "call_type: %s successfully completed" % call_type
                log.info(msg)
                return self.to_instance(response)
            elif (response.status_code == 200 and call_type in ['delete', 'destroy']):
            #delete success
                msg ="call_type: %s successfully completed" % call_type
                log.info(msg)
                return self._try_to_serialize(response)
            elif 200 <= response.status_code <= 299:
                return self._try_to_serialize(response)
        except Exception as e:
            msg = "Exception occoured %s url: %s" % (e, url)
            log.error(msg)
            raise e
344206
def run(self, target, payload, instance=None, hook_id=None, **kwargs):
        
        response = requests.post(
            url=target,
            data=json.dumps(payload, cls=DjangoJSONEncoder),
            headers={'Content-Type': 'application/json'}
        )

        if response.status_code == 410 and hook_id:
            HookModel = get_hook_model()
            hook = HookModel.object.get(id=hook_id)
            hook.delete()
999968
def applyReq(self, request: Request, cons_time: int):
        
        self.execute_hook(NodeHooks.PRE_REQUEST_APPLICATION, request=request,
                          cons_time=cons_time)
        req_handler = self.get_req_handler(txn_type=request.operation[TXN_TYPE])
        seq_no, txn = req_handler.apply(request, cons_time)
        ledger_id = self.ledger_id_for_request(request)
        self.execute_hook(NodeHooks.POST_REQUEST_APPLICATION, request=request,
                          cons_time=cons_time, ledger_id=ledger_id,
                          seq_no=seq_no, txn=txn)
440118
def execute_request(request_type, options)
      request = build_request(request_type)
      response = request.execute(options)

      case request_type
      when :setup_transaction
        SetupTransactionResponse.new(response, config)
      when :recurrent_transaction
        RecurrentTransactionResponse.new(response, config)
      when :refund_transaction
        RefundTransactionResponse.new(response, config)
      when :refund_info
        RefundInfoResponse.new(response, config)
      when :status
        StatusResponse.new(response, config)
      when :cancel
        CancelResponse.new(response, config)
      end
    end
348146
def request(method, uri, data: nil, headers: {}, **kwargs)
      request = Request.new(
        headers: default_headers.merge(headers),
        **kwargs,
        method: method,
        uri: join(uri),
        data: data
      )

      ret = cache.call(request) {|req| adapter.call(req) }
      ret.then do |response|
        if !response.errored?
          process response
        else
          raise ResponseError.from_code(response)
        end
      end
    end
1103835
def build_request(method)
      Request.create(method) do |req|
        req.params  = params.dup
        req.headers = headers.dup
        req.options = options
        yield(req) if block_given?
      end
    end
777257
def call(call, access_token = false, params = {}, risk_token = false, client_ip = false)
      path = call.start_with?('/') ? call : call.prepend('/')
      url  = URI.parse(api_endpoint + path)

      call = Net::HTTP::Post.new(url.path, {
        'Content-Type' => 'application/json',
        'User-Agent'   => 'WePay Ruby SDK'
      })

      unless params.empty?
        call.body = params.to_json
      end

      if access_token then call.add_field('Authorization', "Bearer #{access_token}"); end
      if @api_version then call.add_field('Api-Version', @api_version); end
      if risk_token then call.add_field('WePay-Risk-Token', risk_token); end
      if client_ip then call.add_field('Client-IP', client_ip); end

      make_request(call, url)
    end
486593
def _execute(self, api_command, *, timeout=None):
        """"""

        if api_command.observe:
            self._observe(api_command)
            return

        method = api_command.method
        path = api_command.path
        data = api_command.data
        parse_json = api_command.parse_json
        url = api_command.url(self._host)

        proc_timeout = self._timeout
        if timeout is not None:
            proc_timeout = timeout

        command = self._base_command(method)

        kwargs = {
            'stderr': subprocess.DEVNULL,
            'timeout': proc_timeout,
            'universal_newlines': True,
        }

        if data is not None:
            kwargs['input'] = json.dumps(data)
            command.append('-f')
            command.append('-')
            _LOGGER.debug('Executing %s %s %s: %s', self._host, method, path,
                          data)
        else:
            _LOGGER.debug('Executing %s %s %s', self._host, method, path)

        command.append(url)

        try:
            return_value = subprocess.check_output(command, **kwargs)
        except subprocess.TimeoutExpired:
            raise RequestTimeout() from None
        except subprocess.CalledProcessError as err:
            raise RequestError(
                'Error executing request: {}'.format(err)) from None

        api_command.result = _process_output(return_value, parse_json)
        return api_command.result
310922
def _request(self, method, *relative_path_parts, **kwargs):
        
        uri = self._create_api_uri(*relative_path_parts)
        data = kwargs.get('data', None)
        if data and isinstance(data, dict):
            kwargs['data'] = encode_params(data)
        if self.VERIFY_SSL:
            kwargs.setdefault('verify', COINBASE_CRT_PATH)
        else:
            kwargs.setdefault('verify', False)
        kwargs.update(verify=self.VERIFY_SSL)
        response = getattr(self.session, method)(uri, **kwargs)
        return self._handle_response(response)
690041
def _call(self, method, url, params, uploads):
        
        try:
            data = self._request(method, url, params, uploads)
        except Exception, e:
            self._failed_cb(e)
        else:
            self._completed_cb(data)
1020680
def _api_call(self, path, data={}, http_method=requests.get):
        '''  '''
        log.info('performing api request', path=path)
        response = http_method('/'.join([self.api_url, path]),
                               params={'auth_token': self.api_key},
                               data=data)
        log.debug('{} remaining calls'.format(
            response.headers['x-ratelimit-remaining']))
        return response.json()
250401
def request_raw(self, method, url, params=None, supplied_headers=None):
        
        from stripe import api_version

        if self.api_key:
            my_api_key = self.api_key
        else:
            from stripe import api_key
            my_api_key = api_key

        if my_api_key is None:
            raise error.AuthenticationError(
                'No API key provided. (HINT: set your API key using '
                '"stripe.api_key = <API-KEY>"). You can generate API keys '
                'from the Stripe web interface.  See https://stripe.com/api '
                'for details, or email support@stripe.com if you have any '
                'questions.')

        abs_url = '%s%s' % (self.api_base, url)

        encoded_params = urllib.urlencode(list(_api_encode(params or {})))

        if method == 'get' or method == 'delete':
            if params:
                abs_url = _build_api_url(abs_url, encoded_params)
            post_data = None
        elif method == 'post':
            if supplied_headers is not None and \
                    supplied_headers.get("Content-Type") == \
                    "multipart/form-data":
                generator = MultipartDataGenerator()
                generator.add_params(params or {})
                post_data = generator.get_post_data()
                supplied_headers["Content-Type"] = \
                    "multipart/form-data; boundary=%s" % (generator.boundary,)
            else:
                post_data = encoded_params
        else:
            raise error.APIConnectionError(
                'Unrecognized HTTP method %r.  This may indicate a bug in the '
                'Stripe bindings.  Please contact support@stripe.com for '
                'assistance.' % (method,))

        ua = {
            'bindings_version': version.VERSION,
            'lang': 'python',
            'publisher': 'stripe',
            'httplib': self._client.name,
        }
        for attr, func in [['lang_version', platform.python_version],
                           ['platform', platform.platform],
                           ['uname', lambda: ' '.join(platform.uname())]]:
            try:
                val = func()
            except Exception as e:
                val = "!! %s" % (e,)
            ua[attr] = val

        headers = {
            'X-Stripe-Client-User-Agent': util.json.dumps(ua),
            'User-Agent': 'Stripe/v1 PythonBindings/%s' % (version.VERSION,),
            'Authorization': 'Bearer %s' % (my_api_key,)
        }

        if self.stripe_account:
            headers['Stripe-Account'] = self.stripe_account

        if method == 'post':
            headers['Content-Type'] = 'application/x-www-form-urlencoded'

        if api_version is not None:
            headers['Stripe-Version'] = api_version

        if supplied_headers is not None:
            for key, value in supplied_headers.items():
                headers[key] = value

        util.log_info('Request to Stripe api', method=method, path=abs_url)
        util.log_debug(
            'Post details', post_data=post_data, api_version=api_version)

        rbody, rcode, rheaders = self._client.request(
            method, abs_url, headers, post_data)

        util.log_info(
            'Stripe API response', path=abs_url, response_code=rcode)
        util.log_debug('API response body', body=rbody)
        if 'Request-Id' in rheaders:
            util.log_debug('Dashboard link for request',
                           link=util.dashboard_link(rheaders['Request-Id']))
        return rbody, rcode, rheaders, my_api_key
539503
def execute(self, request):
        '''
        '''
        handle = None
        if request:
            request[0] = command = to_string(request[0]).lower()
            info = COMMANDS_INFO.get(command)
            if info:
                handle = getattr(self.store, info.method_name)
            #
            if self.channels or self.patterns:
                if command not in self.store.SUBSCRIBE_COMMANDS:
                    return self.reply_error(self.store.PUBSUB_ONLY)
            if self.blocked:
                return self.reply_error('Blocked client cannot request')
            if self.transaction is not None and command not in 'exec':
                self.transaction.append((handle, request))
                return self.connection.write(self.store.QUEUED)
        self.execute_command(handle, request)