Given an :class:`httplib.HTTPResponse` instance ``r``, return a
        corresponding :class:`urllib3.response.HTTPResponse` object.

        Remaining parameters are passed to the HTTPResponse constructor, along
        with ``original_response=r``.
541207
def from_httplib(ResponseCls, r, **response_kw):
        
        headers = r.msg

        if not isinstance(headers, HTTPHeaderDict):
            if PY3:  # Python 3
                headers = HTTPHeaderDict(headers.items())
            else:  # Python 2
                headers = HTTPHeaderDict.from_httplib(headers)

        # HTTPResponse objects in Python 3 don't have a .strict attribute
        strict = getattr(r, 'strict', 0)
        resp = ResponseCls(body=r,
                           headers=headers,
                           status=r.status,
                           version=r.version,
                           reason=r.reason,
                           strict=strict,
                           original_response=r,
                           **response_kw)
        return resp
1115638
def extract_cookies_to_jar(jar, request, response):
    
    if not (hasattr(response, '_original_response') and
            response._original_response):
        return
    # the _original_response field is the wrapped httplib.HTTPResponse object,
    req = MockRequest(request)
    # pull out the HTTPMessage with the headers and put it in the mock:
    res = MockResponse(response._original_response.msg)
    jar.extract_cookies(res, req)
238129
def init_original_response(self):
        """"""
        no_cookie_resp = None
        self.is_cookie_necessary = True
        if 'json' in self.request:
            self.request['data'] = json.dumps(self.request.pop('json')).encode(
                self.encoding)
        r1 = self.req.request(
            retry=self.retry, timeout=self.timeout, **self.request)
        if 'headers' in self.request:
            # test is_cookie_necessary
            cookie = self.request['headers'].get('Cookie', None)
            if cookie:
                new_request = deepcopy(self.request)
                new_request['headers']['Cookie'] = ''
                r2 = self.req.request(
                    retry=self.retry, timeout=self.timeout, **new_request)
                no_cookie_resp = self.ensure_response(r2)
        resp = r1.x
        assert resp, ValueError(
            'original_response should not be failed. %s' % self.request)
        self.original_response = self.ensure_response(r1)
        self.encoding = self.encoding or resp.encoding
        if no_cookie_resp == self.original_response:
            self.ignore['headers'].append('Cookie')
            self.is_cookie_necessary = False
        return self.original_response
1050682
def http_resource(self, method, url, params=None, data=None):
        

        url = urllib_parse.urljoin(self.url, url)
        url = url if url.endswith("/") else url + "/"

        headers = None

        if method.lower() in self.unsupported_methods:
            headers = {"X-HTTP-Method-Override": method.upper()}
            method = "POST"

        r = self.session.request(method, url, params=params, data=data, headers=headers)

        r.raise_for_status()

        return r
391122
def copy(self, request, **kwargs):
        # pylint: disable=unused-argument
        '''
        
        '''
        instance = self.copy_instance(self.get_object())
        serializer = self.get_serializer(instance, data=request.data, partial=True)
        serializer.is_valid()
        serializer.save()
        return Response(serializer.data, status.HTTP_201_CREATED).resp
296655
def get_response(self, request, *args, **kwargs):
        ''''''
        # normal process
        response = HttpResponseRedirect(self.redirect_to)
        response[REDIRECT_HEADER_KEY] = self.redirect_to
        return response
75994
def create_response(self, status=201):
        
        self.response = self.get_response_handler()
        self.response.process(self.obj)

        return self._response(self.response.get_response_data(), status=status)
414500
def render_to_response(self, obj, **response_kwargs):
        
        return HttpResponse(self.serialize(obj), content_type='application/json', **response_kwargs)
1265798
def from_response(response):
        
        # Get the httplib.HTTPResponse object
        http_response = response.raw._original_response
        
        # HTTP status line, headers and body as strings
        status_line = "HTTP/1.1 %d %s" % (http_response.status, http_response.reason)
        headers = str(http_response.msg)
        body = http_response.read()

        # Monkey-patch the response object so that it is possible to read from it later.
        response.raw._fp = StringIO(body)

        # Build the payload to create warc file.
        payload = status_line + "\r\n" + headers + "\r\n" + body
        
        headers = {
            "WARC-Type": "response",
            "WARC-Target-URI": response.request.full_url.encode('utf-8')
        }
        return WARCRecord(payload=payload, headers=headers)
446440
def copy(self, cls=None):
        '''  '''
        cls = cls or BaseResponse
        assert issubclass(cls, BaseResponse)
        copy = cls()
        copy.status = self.status
        copy._headers = dict((k, v[:]) for (k, v) in self._headers.items())
        if self._cookies:
            copy._cookies = SimpleCookie()
            copy._cookies.load(self._cookies.output(header=''))
        return copy
1373438
def create_response(request, body=None, status=None, headers=None):
    # type: (BaseHttpRequest, Any, HTTPStatus, dict) -> HttpResponse
    
    if body is None:
        return HttpResponse(None, status or HTTPStatus.NO_CONTENT, headers)
    else:
        body = request.response_codec.dumps(body)
        response = HttpResponse(body, status or HTTPStatus.OK, headers)
        response.set_content_type(request.response_codec.CONTENT_TYPE)
        return response
1180146
def get_or_create_from_legacy_response(self, response, **kwargs):
        '''
        
        '''
        response_cls = self.response_class(**kwargs).get_or_create(**kwargs)
        if not getattr(response_cls, self.column):
            setattr(response_cls, self.column, self.accessor(response))
            _action_and_commit(response_cls, session.add)
688270
def normalize_response(response, request=None):
    
    if isinstance(response, Response):
        return response
    if request is not None and not isinstance(request, Request):
        request = normalize_request(request)

    for normalizer in RESPONSE_NORMALIZERS:
        try:
            return normalizer(response, request=request)
        except TypeError:
            continue

    raise ValueError("Unable to normalize the provided response")
1262717
def get_http_response(self):
        """"""
        return _get_response(
            code=self.code,
            body=str(self),
            headers={
                'Content-Type': 'text/plain'
            }
        )
1091598
def _build_response(self, resp, is_error=False):
        


        def build(resp):

            response = Response()

            # Pass settings over.
            response.config = self.config

            if resp:

                # Fallback to None if there's no staus_code, for whatever reason.
                response.status_code = getattr(resp, 'status', None)

                # Make headers case-insensitive.
                response.headers = CaseInsensitiveDict(getattr(resp, 'headers', None))

                # Start off with our local cookies.
                cookies = self.cookies or dict()

                # Add new cookies from the server.
                if 'set-cookie' in response.headers:
                    cookie_header = response.headers['set-cookie']

                    c = SimpleCookie()
                    c.load(cookie_header)

                    for k,v in c.items():
                        cookies.update({k: v.value})

                # Save cookies in Response.
                response.cookies = cookies

            # Save original resopnse for later.
            response.raw = resp

            if is_error:
                response.error = resp

            response.url = self.full_url

            return response


        history = []

        r = build(resp)
        cookies = self.cookies
        self.cookies.update(r.cookies)

        if r.status_code in REDIRECT_STATI and not self.redirect:

            while (
                ('location' in r.headers) and
                ((r.status_code is codes.see_other) or (self.allow_redirects))
            ):

                if not len(history) < self.config.get('max_redirects'):
                    raise TooManyRedirects()

                history.append(r)

                url = r.headers['location']

                # Handle redirection without scheme (see: RFC 1808 Section 4)
                if url.startswith('//'):
                    parsed_rurl = urlparse(r.url)
                    url = '%s:%s' % (parsed_rurl.scheme, url)

                # Facilitate non-RFC2616-compliant 'location' headers
                # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
                if not urlparse(url).netloc:
                    url = urljoin(r.url, urllib.quote(urllib.unquote(url)))

                # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4
                if r.status_code is codes.see_other:
                    method = 'GET'
                else:
                    method = self.method

                # Remove the cookie headers that were sent.
                headers = self.headers
                try:
                    del headers['Cookie']
                except KeyError:
                    pass

                request = Request(
                    url=url,
                    headers=headers,
                    files=self.files,
                    method=method,
                    params=self.session.params,
                    auth=self._auth,
                    cookies=cookies,
                    redirect=True,
                    config=self.config,
                    timeout=self.timeout,
                    _poolmanager=self._poolmanager,
                    proxies = self.proxies,
                )

                request.send()
                cookies.update(request.response.cookies)
                r = request.response
                self.cookies.update(r.cookies)

            r.history = history

        self.response = r
        self.response.request = self
        self.response.cookies.update(self.cookies)
185738
def _getResponse(self):
        
        resp_dict= dict()
        resp_str = self._conn.read_until("\r\n\r\n", connTimeout)
        for line in resp_str.split("\r\n"):
            mobj = re.match('(\w+):\s*(\S.*)$', line);
            if mobj:
                resp_dict[mobj.group(1)] = mobj.group(2)
            else:
                mobj = re.match('(.*)--END COMMAND--\s*$', line, flags=re.DOTALL)
                if mobj:
                    resp_dict['command_response'] = mobj.group(1)
        return resp_dict
595528
def _get_response(self, **kwargs):
        
        # pylint: disable=E1101
        url = self.read_url + "?output=JSON&token=%s" % self.read_token
        for key in kwargs:
            if key and kwargs[key]:
                val = kwargs[key]
                if isinstance(val, (list, tuple)):
                    val = ",".join(val)
                url += "&%s=%s" % (key, val)
        self._api_url = url
        req = urllib2.urlopen(url)
        data = simplejson.loads(req.read())
        self._api_raw_data = data
        if data and data.get('error', None):
            exceptions.BrightcoveError.raise_exception(
                data['error'])
        if data == None:
            raise exceptions.NoDataFoundError(
                "No data found for %s" % repr(kwargs))
        return data