Example #1
0
    def on_request(self, host: http.Host, headers: http.Headers,
                   method: http.Method, path: http.Path, url: http.URL):
        xray_header = construct_xray_header(headers)

        name = calculate_segment_name(host, self._recorder)

        sampling_decision = calculate_sampling_decision(
            trace_header=xray_header,
            recorder=self._recorder,
            service_name=host,
            method=method,
            path=path)

        segment = self._recorder.begin_segment(name=name,
                                               traceid=xray_header.root,
                                               parent_id=xray_header.parent,
                                               sampling=sampling_decision)

        segment.save_origin_trace_header(xray_header)
        segment.put_http_meta(xray_http.URL, url)
        segment.put_http_meta(xray_http.METHOD, method)
        segment.put_http_meta(xray_http.USER_AGENT, headers.get('User-Agent'))

        client_ip = headers.get('X-Forwarded-For') or headers.get(
            'HTTP_X_FORWARDED_FOR')
        if client_ip:
            segment.put_http_meta(xray_http.CLIENT_IP, client_ip)
            segment.put_http_meta(xray_http.X_FORWARDED_FOR, True)
Example #2
0
async def resource_id_subpath_put(resource_type, resource_id, subpath, body: http.Body, headers: http.Headers,
                                  storage: Storage):
    try:
        if storage.is_file(resource_type, subpath):
            content_type = headers.get('Content-Type')
            revision = headers.get('Revision')
            return await storage.put_file(resource_type, resource_id, subpath, body, revision, content_type)
        else:
            data = JSONParser().parse(body)
            return await storage.put_subpath(resource_type, resource_id, subpath, data)
    except ResourceTypeNotFound:
        raise NotFound({
            'error_code': 'ResourceTypeDoesNotExist',
            'resource_type': resource_type,
            'message': 'Resource type does not exist',
        })
    except ResourceNotFound:
        raise NotFound({
            'error_code': 'ItemDoesNotExist',
            'item_id': resource_id,
            'message': "Item does not exist",
        })
    except WrongRevision as e:
        raise Conflict({
            'error_code': 'WrongRevision',
            'item_id': resource_id,
            'current': e.current,
            'update': e.update,
            'message': (
                'Updating resource {item_id} failed: resource currently has revision {current}, update wants to '
                'update {update}.'
            ),
        })
Example #3
0
 def resolve(self,
             parameter: Parameter,
             headers: http.Headers) -> http.Header:
     name = parameter.name.replace('_', '-')
     assert name in headers or parameter.default != inspect._empty, \
         f"Header: {name} not found!"
     return http.Header(headers.get(name, parameter.default))
Example #4
0
def _get_content_length(headers: http.Headers) -> typing.Optional[int]:
    content_length = headers.get('Content-Length')
    if content_length is not None:
        try:
            return max(0, int(content_length))
        except (ValueError, TypeError):  # pragma: nocover
            pass
    return None  # pragma: nocover
Example #5
0
def handle_option(id, headers: Headers):
    if settings.get('CORS_OPTIONS_REQUESTS_ENABLED', False) is True:
        headers = {
            'Access-Control-Allow-Origin':
            '*',
            'Access-Control-Allow-Headers':
            headers.get('Access-Control-Request-Headers', '*'),
            'Access-Control-Allow-Methods':
            'GET',
        }
        return Response('', headers=headers)
    return Response('', status_code=405)
Example #6
0
def log_custom_headers(id, headers: Headers):
    custom_data = {}
    if 'X-QwantMaps-FocusPosition' in headers:
        pos = headers.get('X-QwantMaps-FocusPosition', '').split(';')
        if len(pos) == 3:
            try:
                lon = float(pos[0])
                lat = float(pos[1])
                zoom = float(pos[2])
                custom_data['lon'] = lon
                custom_data['lat'] = lat
                custom_data['zoom'] = zoom
            except Exception:
                logger.warning(
                    'Invalid data given through "X-QwantMaps-FocusPosition" header',
                    exc_info=True)
    if 'X-QwantMaps-Query' in headers:
        query = headers.get('X-QwantMaps-Query', '')
        if len(query) > 0:
            custom_data['query'] = urllib.parse.unquote_plus(query)
    if 'X-QwantMaps-SuggestionRank' in headers:
        ranking = headers.get('X-QwantMaps-SuggestionRank', '')
        if len(ranking) > 0:
            try:
                ranking = int(ranking)
                custom_data['ranking'] = ranking
            except Exception:
                logger.warning(
                    'Invalid data given through "X-QwantMaps-SuggestionRank" header',
                    exc_info=True)
    if 'X-QwantMaps-QueryLang' in headers:
        lang = headers.get('X-QwantMaps-QueryLang', '')
        if len(lang) > 0:
            custom_data['lang'] = lang
    if len(custom_data) > 0:
        custom_data['id'] = id
        logger.info('Received details about user query',
                    extra={'user_selection': custom_data})
    def resolve(self, content: http.Body, headers: http.Headers):
        if not content:
            return None

        content_type = headers.get('Content-Type')

        try:
            codec = negotiate_content_type(self.codecs, content_type)
        except exceptions.NoCodecAvailable:
            raise exceptions.UnsupportedMediaType()

        try:
            return codec.decode(content, headers=headers)
        except exceptions.ParseError as exc:
            raise exceptions.BadRequest(str(exc))
    def resolve(self, content: Body, headers: Headers, parameter: Parameter):
        if not content:
            raise NotImplementedError

        content_type = headers.get('Content-Type')
        try:
            codec = negotiate_content_type(self.codecs, content_type)
        except exceptions.NoCodecAvailable:
            raise exceptions.UnsupportedMediaType()
        try:
            value = codec.decode(content, headers=headers)
        except exceptions.ParseError as exc:
            raise exceptions.BadRequest(str(exc))
        try:
            return self.handle_parameter(parameter, value)
        except Exception:
            raise exceptions.BadRequest(f"{parameter.name} invalid")
Example #9
0
def get_request_data(headers: http.Headers, injector: Injector,
                     settings: Settings):
    content_type = headers.get('Content-Type')
    if not content_type:
        return None

    media_type, _ = parse_options_header(content_type)
    parser_mapping = {
        parser.media_type: parser
        for parser in settings.get('PARSERS', parsers.DEFAULT_PARSERS)
    }

    if media_type not in parser_mapping:
        raise exceptions.UnsupportedMediaType()

    parser = parser_mapping[media_type]
    return injector.run(parser.parse)
Example #10
0
    def get_response(self, method: http.Method, headers: http.Headers,
                     file_wrapper: FileWrapper) -> http.Response:
        wsgi_style_headers = {
            'HTTP_' + k.upper().replace('-', '_'): v
            for k, v in headers.items()
        }
        response = self._file.get_response(method, wsgi_style_headers)
        if response.file is not None:
            content = file_wrapper(response.file)
        else:
            # We hit this branch for HEAD requests
            content = b''

        response_headers = dict(response.headers)
        content_type = response_headers.pop('Content-Type', None)
        return http.Response(content,
                             status=response.status,
                             headers=response_headers,
                             content_type=content_type)
Example #11
0
async def get_request_data(headers: http.Headers, message: UMIMessage, channels: UMIChannels):
    content_type = headers.get('Content-Type')
    if content_type:
        mimetype, options = parse_options_header(content_type)
    else:
        mimetype, options = None, {}

    if mimetype is None:
        value = None
    elif mimetype == 'application/json':
        body = await get_body(message, channels)
        value = json.loads(body.decode('utf-8'))
    elif mimetype in ('multipart/form-data', 'application/x-www-form-urlencoded'):
        body = await get_body(message, channels)
        stream = io.BytesIO(body)
        content_length = _get_content_length(headers)
        parser = FormDataParser()
        stream, form, files = parser.parse(stream, mimetype, content_length, options)
        value = ImmutableMultiDict(list(form.items()) + list(files.items()))
    else:
        raise exceptions.UnsupportedMediaType()

    return value
Example #12
0
def get_header(name: ParamName, headers: http.Headers):
    return headers.get(name.replace('_', '-'))
Example #13
0
 def _get_mimetype_and_options(headers: http.Headers) -> typing.Tuple[str, dict]:
     return parse_options_header(headers.get('Content-Type'))
Example #14
0
 def get_mimetype_and_options(
         self, headers: http.Headers) -> typing.Tuple[str, dict]:
     content_type = headers.get('Content-Type')
     if content_type:
         return parse_options_header(content_type)
     return '', {}