Dispatches a request to the Asana HTTP API
185475
def request(self, method, path, **options):
        """"""
        options = self._merge_options(options)
        url = options['base_url'] + path
        retry_count = 0
        request_options = self._parse_request_options(options)
        self._add_version_header(request_options)
        while True:
            try:
                response = getattr(self.session, method)(
                    url, auth=self.auth, **request_options)
                if response.status_code in STATUS_MAP:
                    raise STATUS_MAP[response.status_code](response)
                elif 500 <= response.status_code < 600:
                    # Any unhandled 500 is a server error.
                    raise error.ServerError(response)
                else:
                    if options['full_payload']:
                        return response.json()
                    else:
                        return response.json()['data']
            except error.RetryableAsanaError as e:
                if retry_count < options['max_retries']:
                    self._handle_retryable_error(e, retry_count)
                    retry_count += 1
                else:
                    raise e
727545
def call(self, **data):
        
        uri, body, headers = self.prepare(data)
        return self.dispatch(uri, body, headers)
113057
async def _request(
            self,
            method: str,
            url: str,
            *,
            access_token: str = None,
            access_token_expiration: datetime = None,
            headers: dict = None,
            params: dict = None,
            json: dict = None,
            ssl: bool = True) -> dict:
        """"""
        if (access_token_expiration
                and datetime.now() >= access_token_expiration):
            raise TokenExpiredError('Long-lived access token has expired')

        if not headers:
            headers = {}
        headers.update({'Content-Type': 'application/json'})

        if not params:
            params = {}
        if access_token:
            params.update({'access_token': access_token})

        try:
            async with async_timeout.timeout(self.request_timeout):
                async with self._websession.request(
                        method, url, headers=headers, params=params, json=json,
                        ssl=ssl) as resp:
                    resp.raise_for_status()
                    data = await resp.json(content_type=None)
                    _raise_for_remote_status(url, data)
        except ClientError as err:
            raise RequestError(
                'Error requesting data from {0}: {1}'.format(url, err))
        except asyncio.TimeoutError:
            raise RequestError('Timeout during request: {0}'.format(url))

        return data
462983
async def dispatch(self, request, view=None, **kwargs):
        """"""
        # Authorization endpoint
        self.auth = await self.authorize(request, **kwargs)  # noqa

        # Load collection
        self.collection = await self.get_many(request, **kwargs)

        if request.method == 'POST' and view is None:
            return await super(RESTHandler, self).dispatch(request, **kwargs)

        # Load resource
        resource = await self.get_one(request, **kwargs)

        headers = {}

        if request.method == 'GET' and resource is None:

            # Filter resources
            if VAR_WHERE in request.query:
                self.collection = await self.filter(request, **kwargs)

            # Sort resources
            if VAR_SORT in request.query:
                sorting = [(name.strip('-'), name.startswith('-'))
                           for name in request.query[VAR_SORT].split(',')]
                self.collection = await self.sort(*sorting, **kwargs)

            # Paginate resources
            per_page = request.query.get(VAR_PER_PAGE, self.meta.per_page)
            if per_page:
                try:
                    per_page = int(per_page)
                    if per_page:
                        page = int(request.query.get(VAR_PAGE, 0))
                        offset = page * per_page
                        self.collection, total = await self.paginate(request, offset, per_page)
                        headers = make_pagination_headers(
                            request, per_page, page, total, self.meta.page_links)
                except ValueError:
                    raise RESTBadRequest(reason='Pagination params are invalid.')

        response = await super(RESTHandler, self).dispatch(
            request, resource=resource, view=view, **kwargs)
        response.headers.update(headers)
        return response
507898
def dispatch(self, request, *args, **kwargs):
        
        ajax_kwargs = {'mandatory': self.ajax_mandatory}
        if self.json_encoder:
            ajax_kwargs['cls'] = self.json_encoder

        return ajax(**ajax_kwargs)(super(
            AJAXMixin, self).dispatch)(request, *args, **kwargs)
1195501
def _api_request(self, action, data, request_type, headers=None):
        
        if 'file' in data:
            file_data = {'file': open(data['file'], 'rb')}
        else:
            file_data = None

        return self._http_request(action, self._prepare_json_payload(data), request_type, file_data, headers)
530452
def dispatch(self, request, *args, **kwargs):
        
        self.args = args
        self.kwargs = kwargs
        request = self.initialize_request(request, *args, **kwargs)
        self.request = request
        self.headers = self.default_response_headers  # deprecate?

        try:
            self.initial(request, *args, **kwargs)

            # Get the appropriate handler method
            if request.method.lower() in self.http_method_names:
                handler = getattr(self, request.method.lower(),
                                  self.http_method_not_allowed)
            else:
                handler = self.http_method_not_allowed

            response = handler(request, *args, **kwargs)

        except Exception as exc:
            response = self.handle_exception(exc)

        self.response = self.finalize_response(request, response, *args, **kwargs)
        return self.response
294749
def dispatch(self, request, **kwargs):
        '''
        
        '''

        # Check if this is a REST query to pusth the answer to responde in JSON
        if bool(self.request.META.get('HTTP_X_REST', False)):
            self.json = True

        # Check if this is a REST query to add an element
        if self.request.method in ['PUT', 'DELETE']:
            if self.request.method == 'PUT':
                action = 'edit'
            else:
                action = 'delete'

            # Set new method
            self.request.method == 'POST'

            # Find the URL
            target = get_class(resolve("{}/{}".format(self.request.META.get("REQUEST_URI"), action)).func)

            # Make sure we will answer as an API
            target.json = True

            # Lets go for it
            return target.as_view()(self.request, pk=kwargs.get('pk'))

        # Detect if we have to answer in json
        self.__authtoken = (bool(getattr(self.request, "authtoken", False)))
        self.json_worker = self.__authtoken or (self.json is True)

        # Check if this is an AJAX request
        if (request.is_ajax() or self.json_worker) and request.body:
            request.POST = json.loads(request.body)

        # Set class internal variables
        self._setup(request)

        # Call the base implementation
        return super(GenDetail, self).dispatch(request, **kwargs)
572932
def perform_api_request(
        self,
        url,
        method='POST',
        headers=None,
        body=None,
        **kwargs
    ):
        '''
        
        '''
        assert method in ('GET', 'POST')
        if method == 'GET':
            response = self._perform_get(url, headers=headers, **kwargs)
        elif method == 'POST':
            response = self._perform_post(url, headers=headers, data=body, **kwargs)
        return response
635450
def api_call(self, opts, args=None, body=None, **kwargs):
        """"""
        if args:
            path = opts['name'] % args
        else:
            path = opts['name']
        path = '/api/v1%s' % path
        return self._request(
            opts['method'], path=path, payload=body, **kwargs)
1258982
def __call_api(self, path, params=None, api_url=FORECAST_URL):
        
        if not params:
            params = dict()
        payload = {'key': self.api_key}
        payload.update(params)
        url = "%s/%s" % (api_url, path)

        # Add a timeout to the request.
        # The value of 1 second is based on attempting 100 connections to
        # datapoint and taking ten times the mean connection time (rounded up).
        # Could expose to users in the functions which need to call the api.
        #req = requests.get(url, params=payload, timeout=1)
        # The wrapper function __retry_session returns a requests.Session
        # object. This has a .get() function like requests.get(), so the use
        # doesn't change here.

        sess = self.__retry_session()
        req = sess.get(url, params=payload, timeout=1)

        try:
            data = req.json()
        except ValueError:
            raise APIException("DataPoint has not returned any data, this could be due to an incorrect API key")
        self.call_response = data
        if req.status_code != 200:
            msg = [data[m] for m in ("message", "error_message", "status") \
                      if m in data][0]
            raise Exception(msg)
        return data
139901
def _api_action(url, req, data=None):
    """"""
    requisite_headers = {'Accept': 'application/json',
                         'Content-Type': 'application/json'}
    auth = (user, token)

    if req == "GET":
        response = requests.get(url, headers=requisite_headers, auth=auth)
    elif req == "PUT":
        response = requests.put(url, headers=requisite_headers, auth=auth,
                                data=data)
    elif req == "POST":
        response = requests.post(url, headers=requisite_headers, auth=auth,
                                 data=data)
    elif req == "DELETE":
        response = requests.delete(url, headers=requisite_headers, auth=auth)

    return response.status_code, response.text
1343723
def api_get(self, action, data, headers=None):
        
        return self._api_request(action, data, 'GET', headers)
1215081
def http_call(self, url=None, **kwargs):
        
        if not url:
            url = self.search_url
        http_func, arg_name = self.get_http_method_arg_name()
        # Build the argument dictionary to pass in the http function
        _kwargs = {
            arg_name: kwargs,
        }
        # The actual HTTP call
        response = http_func(
            url=url.format(**kwargs),
            headers=self.get_http_headers(),
            **_kwargs
        )
        # Error handling
        if response.status_code != 200:
            logger.warning('Invalid Request for `%s`', response.url)
            # Raising a "requests" exception
            response.raise_for_status()
        return response.json()
921422
def dispatch(self, request, **kwargs):
        '''
        
        '''

        # Delete method must happen with POST not with GET
        if request.method == 'POST':
            # Check if this is a webservice request
            self.__authtoken = (bool(getattr(self.request, "authtoken", False)))
            self.json_worker = self.__authtoken or (self.json is True)
            # Call the base implementation
            return super(GenDelete, self).dispatch(request, **kwargs)
        else:
            json_answer = json.dumps({
                'error': True,
                'errortxt': _('Method not allowed, use POST to delete or DELETE on the detail url'),
                })
            return HttpResponse(json_answer, content_type='application/json')
1134575
def dispatch(self):
        ''
        import flask
        body = flask.request.get_json()
        return self. dispatch_with_args(body, argMap=dict())
999006
def call_api(http_method, path, opts = {})
      request = build_request(http_method, path, opts)
      response = request.run

      if @config.debugging
        @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
      end

      unless response.success?
        if response.timed_out?
          fail ApiError.new('Connection timed out')
        elsif response.code == 0
          # Errors from libcurl will be made visible here
          fail ApiError.new(:code => 0,
                            :message => response.return_message)
        else
          exception_message = nil
          response_json = JSON.parse(response.body) rescue nil
          if response_json.is_a? Hash
            if response_json['errors'].is_a? Array
              response_errors = response_json['errors'].join(', ')
            elsif response_json['error']
              response_errors = response_json['error']
            end
            if response_errors
              exception_message = "#{response.status_message}: #{response_errors}"
            end
          end

          unless exception_message
            exception_message = "#{response.status_message}: [Could not parse errors from response body]"
          end

          fail ApiError.new(:code => response.code,
                            :response_headers => response.headers,
                            :response_body => response.body),
               exception_message
        end
      end

      if opts[:return_type]
        data = deserialize(response, opts[:return_type])
      else
        data = nil
      end
      return data, response.code, response.headers
    end