Treat a notification and guarantee its authenticity.

    :param request_body: The request body in plain text.
    :type request_body: string

    :return: A safe APIResource
    :rtype: APIResource
357328
def treat(request_body):
    
    # Python 3+ support
    if isinstance(request_body, six.binary_type):
        request_body = request_body.decode('utf-8')

    try:
        data = json.loads(request_body)
    except ValueError:
        raise exceptions.UnknownAPIResource('Request body is malformed JSON.')

    unsafe_api_resource = APIResource.factory(data)

    try:
        consistent_api_resource = unsafe_api_resource.get_consistent_resource()
    except AttributeError:
        raise exceptions.UnknownAPIResource('The API resource provided is invalid.')

    return consistent_api_resource
626260
def _req(self, method="get", verb=None, headers={}, params={}, data={}):
        
        url = self.BASE_URL.format(verb=verb)
        request_headers = {"content-type": "application/json"}
        request_params = {"api_key": self.API_KEY}
        request_headers.update(headers)
        request_params.update(params)
        return getattr(requests, method)(
            url, params=request_params, headers=request_headers, data=data
        )
1051889
def process_request_body(fn):
    '''
    
    '''
    @functools.wraps(fn)
    def wrapped(*args, **kwargs):  # pylint: disable=C0111
        if cherrypy.request.process_request_body is not False:
            fn(*args, **kwargs)
    return wrapped
662736
def validate_detector(self, body, params=None):
        
        if body in SKIP_IN_PATH:
            raise ValueError("Empty value passed for a required argument 'body'.")
        return self.transport.perform_request(
            "POST",
            "/_ml/anomaly_detectors/_validate/detector",
            params=params,
            body=body,
        )
544221
private static boolean hasResponseBody(int requestMethod, int responseCode) {
        return requestMethod != Request.Method.HEAD
            && !(HttpStatus.SC_CONTINUE <= responseCode && responseCode < HttpStatus.SC_OK)
            && responseCode != HttpStatus.SC_NO_CONTENT
            && responseCode != HttpStatus.SC_NOT_MODIFIED;
    }
1306394
def handle_request(self, request_text=None):
        

        if request_text is None and \
            os.environ.get('REQUEST_METHOD', None) == 'GET':
            self.handle_get()
        else:
            # POST data is normally available through stdin
            try:
                length = int(os.environ.get('CONTENT_LENGTH', None))
            except (ValueError, TypeError):
                length = -1
            if request_text is None:
                request_text = sys.stdin.read(length)

            self.handle_xmlrpc(request_text)
725154
def handle_request(self, request_text=None):
        

        if request_text is None and \
            os.environ.get('REQUEST_METHOD', None) == 'GET':
            self.handle_get()
        else:
            # POST data is normally available through stdin
            if request_text is None:
                request_text = sys.stdin.read()

            self.handle_xmlrpc(request_text)
1000727
async def send_message(  # type: ignore
        self, request: str, response_expected: bool, **kwargs: Any
    ) -> Response:
        
        headers = dict(self.DEFAULT_HEADERS)
        headers.update(kwargs.pop("headers", {}))

        response = await self.client.fetch(
            self.endpoint, method="POST", body=request, headers=headers, **kwargs
        )

        return Response(response.body.decode(), raw=response)
1038210
def body(self):
        
        if not self._responses:
            return None
        if self._responses[-1].code >= 400:
            return self._error_message()
        return self._deserialize()
917413
def _http_req_body_serialize(self, body, content_type):
        
        if not body or not isinstance(body, (dict, list)):
            return body
        content_type = headers.parse_content_type(content_type)
        if content_type == CONTENT_TYPE_JSON:
            return self.__hcm_json.dumps(body)
        elif content_type == CONTENT_TYPE_MSGPACK:
            return self.__hcm_msgpack.packb(body)
        raise ValueError('Unsupported Content Type')
349235
def check_that_request_is_timely(raw_body)
      request_json = JSON.parse(raw_body)

      raise AlexaVerifier::InvalidRequestError, 'Timestamp field not present in request' if request_json.fetch('request', {}).fetch('timestamp', nil).nil?

      request_is_timely = (Time.parse(request_json['request']['timestamp'].to_s) >= (Time.now - REQUEST_THRESHOLD))
      raise AlexaVerifier::InvalidRequestError, "Request is from more than #{REQUEST_THRESHOLD} seconds ago" unless request_is_timely
    end
1048043
def send(self, message):
        
        body = {
            'notificationType': self._notification_type,
            'priority': self._priority,
            'isOrganization': self._is_organization,
            'message': message,
        }

        if self._recipients:
            body['recipients'] = self._recipients

        self._tcex.log.debug('notification body: {}'.format(json.dumps(body)))

        # create our tcex resource
        resource = resource = self._tcex.resource('Notification')
        resource.http_method = 'POST'
        resource.body = json.dumps(body)

        results = resource.request()  # do the request
        if results.get('response').status_code == 200:
            # everything worked
            response = results.get('response').json()
        elif results.get('response').status_code == 400:
            # failed..but known... user doesn't exist
            # just return and let calling app handle it
            err = 'Failed to send notification ({})'.format(results.get('response').text)
            self._tcex.log.error(err)
            response = results.get('response').json()
        else:
            # somekind of unknown error...raise
            err = 'Failed to send notification ({})'.format(results.get('response').text)
            self._tcex.log.error(err)
            raise RuntimeError(err)
        return response
858847
async def _send_plain_text(self, request: Request, stack: Stack):
        

        await self._send_text(request, stack, None)
628347
def validate(self, body, params=None):
        
        if body in SKIP_IN_PATH:
            raise ValueError("Empty value passed for a required argument 'body'.")
        return self.transport.perform_request(
            "POST", "/_ml/anomaly_detectors/_validate", params=params, body=body
        )
1363495
def request_payload(cls, request, request_id):
        ''''''
        payload = {
            'jsonrpc': '2.0',
            'method': request.method,
        }
        # A notification?
        if request_id is not None:
            payload['id'] = request_id
        # Preserve empty dicts as missing params is read as an array
        if request.args or request.args == {}:
            payload['params'] = request.args
        return payload
1287035
def _verify_client_authentication(self, request_body, http_headers=None):
        # type (str, Optional[Mapping[str, str]] -> Mapping[str, str]
        
        if http_headers is None:
            http_headers = {}
        token_request = dict(parse_qsl(request_body))
        token_request['client_id']  = verify_client_authentication(self.clients, token_request, http_headers.get('Authorization'))
        return token_request
440675
def post(self, url, post_params=None):
        
        post_params['token'] = self.token
        params = urlencode(post_params)
        logger.debug('Making POST request to %s with body %s', url, params)
        return requests.post(url, data=params)