예제 #1
0
    def send(self,
             request,
             stream=None,
             timeout=None,
             verify=None,
             cert=None,
             proxies=None):
        pathname = url_to_path(request.url)

        resp = Response()
        resp.status_code = 200
        resp.url = request.url

        try:
            stats = os.stat(pathname)
        except OSError as exc:
            resp.status_code = 404
            resp.raw = exc
        else:
            modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
            content_type = mimetypes.guess_type(pathname)[0] or "text/plain"
            resp.headers = CaseInsensitiveDict({
                "Content-Type": content_type,
                "Content-Length": stats.st_size,
                "Last-Modified": modified,
            })

            resp.raw = open(pathname, "rb")
            resp.close = resp.raw.close

        return resp
예제 #2
0
 def __end_request(self, response: Response):
     print(f"Request - status code: {response.status_code}")
     print(response.request.headers)
     print(response.cookies)
     try:
         self.json_printer(response.json())
         return response.json()
     except json.decoder.JSONDecodeError as eMsg:
         print(f"json.decoder.JSONDecodeError: {eMsg}")
         self.json_printer(response.json())
         return response.json()
예제 #3
0
    def send(self, request, **kwargs):
        resp = Response()
        (_, _, _dir) = request.url.partition('://')
        if _dir is None or len(_dir) == 0:
            raise ValueError("not a directory url: {}".format(request.url))
        resp.raw = six.BytesIO(six.b(_dir))
        resp.status_code = 200
        resp.reason = "OK"
        resp.headers = {}
        resp.url = request.url

        return resp
예제 #4
0
    def parse_response(self, response: Response) -> dict:
        """Parses response's json object. Checks configuration in order to parse a concrete node or the whole response.

        :param response: request's response that contains a valid json

        :rtype: dict
        """

        try:
            data = response.json()
            if self.data:
                data = data.get(self.data, {})
            return data
        except ValueError:
            logger.warning("Response.content is not a valid json {}".format(response.content))
            return {}
예제 #5
0
def bulk_operation_response_handler(
        response: Response,
        unpack_value: str = None
) -> Union[PartialSuccess, Success, MstrException]:
    """Handle partial success and other statuses from bulk operation."""
    response_body = response.json()
    if response.ok and unpack_value:
        response_body = response_body[unpack_value]

    if response.status_code == 200:
        err = Success(response_body)
    elif response.status_code == 207:
        err = PartialSuccess(response_body)
    else:
        err = MstrException(response_body)

    if config.verbose:
        logger.error(err)
    return err
예제 #6
0
    def send(self, request, stream=False, timeout=None, verify=True,
             cert=None, proxies=None):

        # Prepare the request to send to the app.

        # webob will include the port into the HTTP_HOST header by default.
        #
        # It's not desirable, so let's insert it into the environment
        # manually. But only do this if the user hasn't set an explicit host
        # name.
        environ = {}
        if 'HTTP_HOST' not in self.app.extra_environ:
            parsed = urlparse(request.url)
            environ['HTTP_HOST'] = parsed.netloc

        non_body_methods = set('GET HEAD DELETE OPTIONS'.split())
        with_body_methods = set('POST PUT PATCH'.split())

        wtparams = dict(headers=request.headers, extra_environ=environ,
                        url=request.url, expect_errors=True)
        if request.method in with_body_methods:
            wtparams['params'] = request.body

        if stream and not issubclass(self.app.RequestClass, PyriformTestRequest):
            warnings.warn('Passing a TestApp instance to WSGIAdapter prevents '
                          'streamed requests from streaming content in real time.',
                          RuntimeWarning)

        # Delegate to the appropriate handler if we have one.
        if request.method in non_body_methods or \
                request.method in with_body_methods:
            handler = getattr(self.app, request.method.lower())
        else:
            # This is an internal method, but most handlers delegate to it, so
            # we'll just make use of it for unknown methods.
            wtparams['method'] = request.method
            handler = self.app._gen_request

        # We only care about the read timeout.
        if isinstance(timeout, tuple):
            _, timeout = timeout

        wtresp = self._invoke_handler(handler, wtparams, timeout)

        # Convert the response.
        resp = Response()
        resp.status_code = wtresp.status_code
        resp.reason = wtresp.status.split(' ', 1)[1]
        resp.url = request.url

        # Although HTTPHeaderDict is better positioned to handle multiple headers with the same
        # name, requests doesn't use this type for responses. Instead, it uses its own dictionary
        # type for headers (which doesn't have multiple header value support).
        #
        # But because it uses the HTTPHeaderDict object, all multiple value headers will be
        # compiled together, so that's what we store here (to be consistent with requests).
        #
        # It would be nice to use HTTPHeaderDict for the response, but we don't want to provide a
        # different object with a different API.
        resp.headers.update(HTTPHeaderDict(wtresp.headerlist))

        resp.request = request
        resp.raw = IterStringIO(wtresp._app_iter)
        return resp