Converts the given URL to a resource.

    :param request: Request object (required for the host name part of the
      URL). If this is not given, the current request is used.
328023
def url_to_resource(url, request=None):
    
    if request is None:
        request = get_current_request()
#    cnv = request.registry.getAdapter(request, IResourceUrlConverter)
    reg = get_current_registry()
    cnv = reg.getAdapter(request, IResourceUrlConverter)
    return cnv.url_to_resource(url)
951745
def request(self, url, method="get", format="json", data=None,
                expected_status=None, headers=None, use_xpost=True, **options):
        
        if expected_status is None:
            if method == "get":
                expected_status = 200
            elif method == "post":
                expected_status = 201
            else:
                raise ValueError("No expected status supplied and method unknown.")

        if not url.startswith("http"):
            url = "{self.host}/api/v4/{url}".format(**locals())
        if format is not None:
            options = dict({'format': format}, **options)
        options = {field: value for field, value in options.items() if value is not None}
        headers = dict(headers or {}, Authorization="Token {}".format(self.token))
        #headers['Accept-encoding'] = 'gzip'

        if method == "get" and use_xpost:
            # If method is purely GET, we can use X-HTTP-METHOD-OVERRIDE to send our
            # query via POST. This allows for a large number of parameters to be supplied
            assert(data is None)

            headers.update({"X-HTTP-METHOD-OVERRIDE": method})
            data = options
            options = None
            method = "post"

        r = requests.request(method, url, data=data, params=options, headers=headers)

        log.debug(
            "HTTP {method} {url} (options={options!r}, data={data!r},"
            "headers={headers}) -> {r.status_code}".format(**locals())
        )
        return check(r, expected_status=expected_status)
296872
def _get_request(self, url, params=None, **kwargs):
        
        '''  '''
        
    # construct request kwargs
        request_kwargs = {
            'method': 'GET',
            'url': url,
            'params': params
        }
        for key, value in kwargs.items():
            request_kwargs[key] = value

    # send request and handle response
        return self._request(**request_kwargs)
70717
def send_request(self, request):
        
        logger.debug("send_request - " + str(request))
        assert isinstance(request, Request)
        try:
            host, port = request.destination
        except AttributeError:
            return

        request.timestamp = time.time()
        transaction = Transaction(request=request, timestamp=request.timestamp)
        if transaction.request.type is None:
            transaction.request.type = defines.Types["CON"]

        if transaction.request.mid is None:
            transaction.request.mid = self.fetch_mid()

        key_mid = str_append_hash(host, port, request.mid)
        self._transactions[key_mid] = transaction

        key_token = str_append_hash(host, port, request.token)
        self._transactions_token[key_token] = transaction

        return self._transactions[key_mid]
989388
def init_resource(self, request, res):
        
        res.location_query = request.uri_query
        res.payload = (request.content_type, request.payload)
        return res
321364
def process_request(self, request):
        
        domain, host = map(lower,
            (self.get_domain_for_request(request), request.get_host()))

        pattern = r'^(?:(?P<subdomain>.*?)\.)?%s(?::.*)?$' % re.escape(domain)
        matches = re.match(pattern, host)

        if matches:
            request.subdomain = matches.group('subdomain')
        else:
            request.subdomain = None
            logger.warning('The host %s does not belong to the domain %s, '
                'unable to identify the subdomain for this request',
                request.get_host(), domain)
197220
def _get(self, url, query=None, **kwargs):
        

        return self._request('get', url, query, **kwargs)
119681
def source(self, request):
        
        if isinstance(self.location, six.string_types):
            value = getattr(request, self.location, MultiDict())
            if callable(value):
                value = value()
            if value is not None:
                return value
        else:
            values = MultiDict()
            for l in self.location:
                value = getattr(request, l, None)
                if callable(value):
                    value = value()
                if value is not None:
                    values.update(value)
            return values

        return MultiDict()
319790
def get_request(self, url):
        
        if isinstance(url, string_types):
            url = urllib2.Request(url, headers={'Accept-encoding': 'identity'})
        return url
783793
def url(self):
        ''''''
        return URL.from_url(self.request.url, show_host=self.show_host)
855228
def get_host(request):
    
    # We try three options, in order of decreasing preference.
    if settings.USE_X_FORWARDED_HOST and (
            'HTTP_X_FORWARDED_HOST' in request.META):
        host = request.META['HTTP_X_FORWARDED_HOST']
    elif 'HTTP_HOST' in request.META:
        host = request.META['HTTP_HOST']
    else:
        # Reconstruct the host using the algorithm from PEP 333.
        host = request.META['SERVER_NAME']
        server_port = str(request.META['SERVER_PORT'])
        if server_port != (request.is_secure() and '443' or '80'):
            host = '%s:%s' % (host, server_port)
    return host
719480
def request(self, request):
        

        url = "{}{}".format(self._base_url, request.path)

        timeout = self.poll_timeout

        if request.stream is True:
            timeout = self.stream_timeout

        try:
            http_response = self._session.request(
                request.method,
                url,
                headers=self._headers,
                params=request.params,
                data=request.body,
                stream=request.stream,
                timeout=timeout
            )
        except requests.exceptions.ConnectionError:
            raise V20ConnectionError(url)
        except requests.exceptions.ConnectTimeout:
            raise V20Timeout(url, "connect")
        except requests.exceptions.ReadTimeout:
            raise V20Timeout(url, "read")

        request.headers = http_response.request.headers

        response = Response(
            request,
            request.method,
            http_response.url,
            http_response.status_code,
            http_response.reason,
            http_response.headers
        )

        if request.stream:
            response.set_line_parser(
                request.line_parser
            )

            response.set_lines(
                http_response.iter_lines(
                    self.stream_chunk_size
                )
            )
        else:
            response.set_raw_body(http_response.text)

        return 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
269948
def convert_http_request(request, referrer_host=None):
    '''
    '''
    new_request = urllib.request.Request(
        request.url_info.url,
        origin_req_host=referrer_host,
    )

    for name, value in request.fields.get_all():
        new_request.add_header(name, value)

    return new_request
1097568
def page(self, method, uri, params=None, data=None, headers=None, auth=None, timeout=None,
             allow_redirects=False):
        
        return self.request(
            method,
            uri,
            params=params,
            data=data,
            headers=headers,
            auth=auth,
            timeout=timeout,
            allow_redirects=allow_redirects,
        )
1233763
def _request(self, url, params=None):
        

        response = get(url, params=params, headers=self.headers, timeout=30)

        if response.status_code != 200:
            raise APIError('Request to {} returned {}'.format(response.url, response.status_code))

        response = response.json()

        error_text = response['service_meta']['error_text']
        if error_text:
            raise APIError(error_text)

        return response
1054330
def _SerializeRequest(self, request):
        
        # Construct status line
        parsed = urllib_parse.urlsplit(request.url)
        request_line = urllib_parse.urlunsplit(
            ('', '', parsed.path, parsed.query, ''))
        if not isinstance(request_line, six.text_type):
            request_line = request_line.decode('utf-8')
        status_line = u' '.join((
            request.http_method,
            request_line,
            u'HTTP/1.1\n'
        ))
        major, minor = request.headers.get(
            'content-type', 'application/json').split('/')
        msg = mime_nonmultipart.MIMENonMultipart(major, minor)

        # MIMENonMultipart adds its own Content-Type header.
        # Keep all of the other headers in `request.headers`.
        for key, value in request.headers.items():
            if key == 'content-type':
                continue
            msg[key] = value

        msg['Host'] = parsed.netloc
        msg.set_unixfrom(None)

        if request.body is not None:
            msg.set_payload(request.body)

        # Serialize the mime message.
        str_io = six.StringIO()
        # maxheaderlen=0 means don't line wrap headers.
        gen = generator.Generator(str_io, maxheaderlen=0)
        gen.flatten(msg, unixfrom=False)
        body = str_io.getvalue()

        return status_line + body