예제 #1
0
파일: responses.py 프로젝트: itajaja/moto
    def _on_request(self, adapter, request, **kwargs):
        match = self._find_match(request)
        # TODO(dcramer): find the correct class for this
        if match is None:
            error_msg = 'Connection refused: {0} {1}'.format(request.method,
                                                             request.url)
            response = ConnectionError(error_msg)
            response.request = request

            self._calls.add(request, response)
            raise response

        if 'body' in match and isinstance(match['body'], Exception):
            self._calls.add(request, match['body'])
            raise match['body']

        headers = {}
        if match['content_type'] is not None:
            headers['Content-Type'] = match['content_type']

        if 'callback' in match:  # use callback
            status, r_headers, body = match['callback'](request)
            if isinstance(body, six.text_type):
                body = body.encode('utf-8')
            body = BufferIO(body)
            headers.update(r_headers)

        elif 'body' in match:
            if match['adding_headers']:
                headers.update(match['adding_headers'])
            status = match['status']
            body = BufferIO(match['body'])

        response = HTTPResponse(
            status=status,
            reason=six.moves.http_client.responses[status],
            body=body,
            headers=headers,
            preload_content=False,
            # Need to not decode_content to mimic requests
            decode_content=False,
        )

        response = adapter.build_response(request, response)
        if not match.get('stream'):
            response.content  # NOQA

        try:
            resp_cookies = Cookies.from_request(response.headers['set-cookie'])
            response.cookies = cookiejar_from_dict(dict(
                (v.name, v.value)
                for _, v
                in resp_cookies.items()
            ))
        except (KeyError, TypeError):
            pass

        self._calls.add(request, response)

        return response
예제 #2
0
파일: responses.py 프로젝트: 2rs2ts/moto
    def _on_request(self, adapter, request, **kwargs):
        match = self._find_match(request)
        # TODO(dcramer): find the correct class for this
        if match is None:
            error_msg = 'Connection refused: {0} {1}'.format(request.method,
                                                             request.url)
            response = ConnectionError(error_msg)
            response.request = request

            self._calls.add(request, response)
            raise response

        if 'body' in match and isinstance(match['body'], Exception):
            self._calls.add(request, match['body'])
            raise match['body']

        headers = {}
        if match['content_type'] is not None:
            headers['Content-Type'] = match['content_type']

        if 'callback' in match:  # use callback
            status, r_headers, body = match['callback'](request)
            if isinstance(body, six.text_type):
                body = body.encode('utf-8')
            body = BufferIO(body)
            headers.update(r_headers)

        elif 'body' in match:
            if match['adding_headers']:
                headers.update(match['adding_headers'])
            status = match['status']
            body = BufferIO(match['body'])

        response = HTTPResponse(
            status=status,
            reason=six.moves.http_client.responses[status],
            body=body,
            headers=headers,
            preload_content=False,
        )

        response = adapter.build_response(request, response)
        if not match.get('stream'):
            response.content  # NOQA

        try:
            resp_cookies = Cookies.from_request(response.headers['set-cookie'])
            response.cookies = cookiejar_from_dict(dict(
                (v.name, v.value)
                for _, v
                in resp_cookies.items()
            ))
        except (KeyError, TypeError):
            pass

        self._calls.add(request, response)

        return response
예제 #3
0
    def _on_request(self, adapter, request, **kwargs):
        match = self._find_match(request)
        resp_callback = self.response_callback

        if match is None:
            if request.url.startswith(self.passthru_prefixes):
                logger.info('request.allowed-passthru',
                            extra={
                                'url': request.url,
                            })
                return _real_send(adapter, request)

            error_msg = 'Connection refused: {0} {1}'.format(
                request.method, request.url)
            response = ConnectionError(error_msg)
            response.request = request

            self._calls.add(request, response)
            response = resp_callback(response) if resp_callback else response
            raise response

        try:
            response = adapter.build_response(
                request,
                match.get_response(request),
            )
        except Exception as response:
            match.call_count += 1
            self._calls.add(request, response)
            response = resp_callback(response) if resp_callback else response
            raise

        if not match.stream:
            response.content  # NOQA

        try:
            resp_cookies = Cookies.from_request(response.headers['set-cookie'])
            response.cookies = cookiejar_from_dict(
                dict((v.name, v.value) for _, v in resp_cookies.items()))
        except (KeyError, TypeError):
            pass

        response = resp_callback(response) if resp_callback else response
        match.call_count += 1
        self._calls.add(request, response)
        return response
예제 #4
0
    def _on_request(self, adapter, request, **kwargs):
        match = self._find_match(request)
        # TODO(dcramer): find the correct class for this
        if match is None:
            error_msg = "Connection refused: {0} {1}".format(request.method, request.url)
            response = ConnectionError(error_msg)

            self._calls.add(request, response)
            raise response

        if "body" in match and isinstance(match["body"], Exception):
            self._calls.add(request, match["body"])
            raise match["body"]

        headers = {"Content-Type": match["content_type"]}

        if "callback" in match:  # use callback
            status, r_headers, body = match["callback"](request)
            if isinstance(body, six.text_type):
                body = body.encode("utf-8")
            body = BufferIO(body)
            headers.update(r_headers)

        elif "body" in match:
            if match["adding_headers"]:
                headers.update(match["adding_headers"])
            status = match["status"]
            body = BufferIO(match["body"])

        response = HTTPResponse(status=status, body=body, headers=headers, preload_content=False)

        response = adapter.build_response(request, response)
        if not match.get("stream"):
            response.content  # NOQA

        try:
            resp_cookies = Cookies.from_request(response.headers["set-cookie"])
            response.cookies = cookiejar_from_dict(dict((v.name, v.value) for _, v in resp_cookies.items()))
        except (KeyError, TypeError):
            pass

        self._calls.add(request, response)

        return response
예제 #5
0
    def _on_request(self, adapter, request, **kwargs):
        match = self._find_match(request)
        resp_callback = self.response_callback

        if match is None:
            if request.url.startswith(self.passthru_prefixes):
                logger.info("request.allowed-passthru",
                            extra={"url": request.url})
                return _real_send(adapter, request, **kwargs)

            error_msg = ("Connection refused by Responses: {0} {1} doesn't "
                         "match Responses Mock".format(request.method,
                                                       request.url))
            response = ConnectionError(error_msg)
            response.request = request

            self._calls.add(request, response)
            response = resp_callback(response) if resp_callback else response
            raise response

        try:
            response = adapter.build_response(request,
                                              match.get_response(request))
        except Exception as response:
            match.call_count += 1
            self._calls.add(request, response)
            response = resp_callback(response) if resp_callback else response
            raise

        if not match.stream:
            response.content  # NOQA

        try:
            response.cookies = _cookies_from_headers(response.headers)
        except (KeyError, TypeError):
            pass

        response = resp_callback(response) if resp_callback else response
        match.call_count += 1
        self._calls.add(request, response)
        return response
예제 #6
0
    def _on_request(self, adapter, request, **kwargs):
        match = self._find_match(request)
        resp_callback = self.response_callback

        if match is None:
            if request.url.startswith(self.passthru_prefixes):
                logger.info("request.allowed-passthru", extra={"url": request.url})
                return _real_send(adapter, request, **kwargs)

            error_msg = (
                "Connection refused by Responses: {0} {1} doesn't "
                "match Responses Mock".format(request.method, request.url)
            )
            response = ConnectionError(error_msg)
            response.request = request

            self._calls.add(request, response)
            response = resp_callback(response) if resp_callback else response
            raise response

        try:
            response = adapter.build_response(request, match.get_response(request))
        except Exception as response:
            match.call_count += 1
            self._calls.add(request, response)
            response = resp_callback(response) if resp_callback else response
            raise

        if not match.stream:
            response.content  # NOQA

        try:
            response.cookies = _cookies_from_headers(response.headers)
        except (KeyError, TypeError):
            pass

        response = resp_callback(response) if resp_callback else response
        match.call_count += 1
        self._calls.add(request, response)
        return response
예제 #7
0
    def _on_request(self, session, request, **kwargs):
        match = self._find_match(request)
        # TODO(dcramer): find the correct class for this
        if match is None:
            error_msg = 'Connection refused: {0} {1}'.format(
                request.method, request.url)
            response = ConnectionError(error_msg)

            self._calls.add(request, response)
            raise response

        if 'body' in match and isinstance(match['body'], Exception):
            self._calls.add(request, match['body'])
            raise match['body']

        headers = {
            'Content-Type': match['content_type'],
        }

        if 'callback' in match:  # use callback
            status, r_headers, body = match['callback'](request)
            if isinstance(body, six.text_type):
                body = body.encode('utf-8')
            body = BufferIO(body)
            headers.update(r_headers)

        elif 'body' in match:
            if match['adding_headers']:
                headers.update(match['adding_headers'])
            status = match['status']
            body = BufferIO(match['body'])

        response = HTTPResponse(
            status=status,
            body=body,
            headers=headers,
            preload_content=False,
        )

        adapter = session.get_adapter(request.url)

        response = adapter.build_response(request, response)
        if not match.get('stream'):
            response.content  # NOQA

        try:
            resp_cookies = Cookies.from_request(response.headers['set-cookie'])
            response.cookies = cookiejar_from_dict(
                dict((v.name, v.value) for _, v in resp_cookies.items()))
            session.cookies = response.cookies
        except (KeyError, TypeError):
            pass

        self._calls.add(request, response)

        if kwargs.get('allow_redirects') and response.is_redirect:
            # include redirect resolving logic from requests.sessions.Session
            keep_kws = ('stream', 'timeout', 'cert', 'proxies')
            resolve_kwargs = dict([(k, v) for (k, v) in kwargs.items()
                                   if k in keep_kws])
            # this recurses if response.is_redirect,
            # but limited by session.max_redirects
            gen = session.resolve_redirects(response, request,
                                            **resolve_kwargs)
            history = [resp for resp in gen]

            # Shuffle things around if there's history.
            if history:
                # Insert the first (original) request at the start
                history.insert(0, response)
                # Get the last request made
                response = history.pop()
                response.history = history

        return response
예제 #8
0
    def _on_request(self, session, request, **kwargs):
        match = self._find_match(request)
        # TODO(dcramer): find the correct class for this
        if match is None:
            error_msg = 'Connection refused: {0} {1}'.format(request.method,
                                                             request.url)
            response = ConnectionError(error_msg)

            self._calls.add(request, response)
            raise response

        if 'body' in match and isinstance(match['body'], Exception):
            self._calls.add(request, match['body'])
            raise match['body']

        headers = {
            'Content-Type': match['content_type'],
        }

        if 'callback' in match:  # use callback
            status, r_headers, body = match['callback'](request)
            if isinstance(body, six.text_type):
                body = body.encode('utf-8')
            body = BufferIO(body)
            headers.update(r_headers)

        elif 'body' in match:
            if match['adding_headers']:
                headers.update(match['adding_headers'])
            status = match['status']
            body = BufferIO(match['body'])

        response = HTTPResponse(
            status=status,
            body=body,
            headers=headers,
            preload_content=False,
        )

        adapter = session.get_adapter(request.url)

        response = adapter.build_response(request, response)
        if not match.get('stream'):
            response.content  # NOQA

        try:
            resp_cookies = Cookies.from_request(response.headers['set-cookie'])
            response.cookies = cookiejar_from_dict(dict(
                (v.name, v.value)
                for _, v
                in resp_cookies.items()
            ))
            session.cookies = response.cookies
        except (KeyError, TypeError):
            pass

        self._calls.add(request, response)

        if kwargs.get('allow_redirects') and response.is_redirect:
            # include redirect resolving logic from requests.sessions.Session
            keep_kws = ('stream', 'timeout', 'cert', 'proxies')
            resolve_kwargs = dict([(k, v) for (k, v) in kwargs.items() if
                                   k in keep_kws])
            # this recurses if response.is_redirect,
            # but limited by session.max_redirects
            gen = session.resolve_redirects(response, request,
                                            **resolve_kwargs)
            history = [resp for resp in gen]

            # Shuffle things around if there's history.
            if history:
                # Insert the first (original) request at the start
                history.insert(0, response)
                # Get the last request made
                response = history.pop()
                response.history = history

        return response