Пример #1
0
    def encode_params(self, data=None, **kwargs):
        """
        Encode parameters in a piece of data.
        Will successfully encode parameters when passed as a dict or a list of
        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
        if parameters are supplied as a dict.
        """
        collection_format = kwargs.get("collection_format",
                                       self.collection_format)
        output_str = kwargs.get("output_str", self.output_str)
        sort = kwargs.get("sort", self.sort)

        if data is None:
            return "", self.content_type
        elif isinstance(data, (str, bytes)):
            return data, self.content_type
        elif hasattr(data, 'read'):
            return data, self.content_type
        elif collection_format == 'multi' and hasattr(data, '__iter__'):
            result = []
            for k, vs in to_key_val_list(data, sort=sort):
                if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):
                    vs = [vs]
                for v in vs:
                    result.append(
                        (k.encode('utf-8') if isinstance(k, str) else k,
                         v.encode('utf-8') if isinstance(v, str) else
                         to_string(v, lang=output_str)))
            return urlencode(result, doseq=True), self.content_type
        elif collection_format == 'encoded' and hasattr(data, '__iter__'):
            return urlencode(data, doseq=False), self.content_type
        elif hasattr(data, '__iter__'):
            results = []
            for k, vs in to_key_val_dict(data).items():
                if isinstance(vs, list):
                    v = self.COLLECTION_SEPARATORS[collection_format].join(
                        quote_plus(e) for e in vs)
                    key = k + '[]'
                else:
                    v = quote_plus(vs)
                    key = k
                results.append("%s=%s" % (key, v))

            return '&'.join(results), self.content_type
        else:
            return data, self.content_type
Пример #2
0
    def encode_params(self, data=None, **kwargs):
        """
        Encode parameters in a piece of data.
        Will successfully encode parameters when passed as a dict or a list of
        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
        if parameters are supplied as a dict.
        """
        collection_format = kwargs.get("collection_format", self.collection_format)
        output_str = kwargs.get("output_str", self.output_str)
        sort = kwargs.get("sort", self.sort)

        if data is None:
            return "", self.content_type
        elif isinstance(data, (str, bytes)):
            return data, self.content_type
        elif hasattr(data, 'read'):
            return data, self.content_type
        elif collection_format == 'multi' and hasattr(data, '__iter__'):
            result = []
            for k, vs in to_key_val_list(data, sort=sort):
                if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):
                    vs = [vs]
                for v in vs:
                    result.append(
                        (k.encode('utf-8') if isinstance(k, str) else k,
                         v.encode('utf-8') if isinstance(v, str) else to_string(v, lang=output_str)))
            return urlencode(result, doseq=True), self.content_type
        elif collection_format == 'encoded' and hasattr(data, '__iter__'):
            return urlencode(data, doseq=False), self.content_type
        elif hasattr(data, '__iter__'):
            results = []
            for k, vs in to_key_val_dict(data).items():
                if isinstance(vs, list):
                    v = self.COLLECTION_SEPARATORS[collection_format].join(quote_plus(e) for e in vs)
                    key = k + '[]'
                else:
                    v = quote_plus(vs)
                    key = k
                results.append("%s=%s" % (key, v))

            return '&'.join(results), self.content_type
        else:
            return data, self.content_type
Пример #3
0
def request_from_context(context):
    """
    Do http requests from context.

    :param context: request context.
    """
    new_context = copy.deepcopy(context)
    assert new_context.method in ALLOWED_METHODS

    new_context.url_path = generate_url_path(
        new_context.url_path,
        prefix=new_context.prefix_url_path,
        format_suffix=new_context.url_path_format,
        **new_context.url_path_params)

    if new_context.body_params or new_context.files:
        body, content_type = new_context.renderer.encode_params(
            new_context.body_params, files=new_context.files)
        if new_context.update_content_type and HttpSdk.CONTENT_TYPE_HEADER_NAME not in new_context.headers:
            new_context.headers[
                HttpSdk.CONTENT_TYPE_HEADER_NAME] = content_type
    else:
        body = None

    authentication_instances = new_context.authentication_instances
    for auth_obj in authentication_instances:
        new_context = auth_obj.apply_authentication(new_context)

    if HttpSdk.COOKIE_HEADER_NAME not in new_context.headers and not new_context.cookie.is_empty(
    ):
        new_context.headers[
            HttpSdk.
            COOKIE_HEADER_NAME] = new_context.cookie.as_cookie_header_value()

    url = "%s%s" % (new_context.host, new_context.url_path)
    if new_context.query_params:
        url += "?%s" % (urlencode(new_context.query_params))

    log_print_request(new_context.method, url, new_context.query_params,
                      new_context.headers, body)
    # ensure method and url are native str
    r = HttpSdk.get_pool_manager(
        new_context.proxy, ssl_verify=new_context.ssl_verify).request(
            convert_unicode_to_native_str(new_context.method),
            convert_unicode_to_native_str(url),
            body=body,
            headers=HttpSdk.convert_headers_to_native_str(new_context.headers),
            redirect=new_context.redirect,
            timeout=new_context.timeout)
    log_print_response(r.status, r.data, r.headers)
    r = new_context.response_class(r)
    return r
Пример #4
0
    def http_request_from_context(context, **kwargs):
        """
        Method to do http requests from context.

        :param context: request context.
        """
        context.method = context.method.upper()
        assert context.method in ALLOWED_METHODS

        context.url_path = generate_url_path(
            context.url_path,
            prefix=context.prefix_url_path,
            format_suffix=context.url_path_format,
            **context.url_path_params
        )

        if context.body_params or context.files:
            body, content_type = context.renderer.encode_params(context.body_params, files=context.files)
            if context.update_content_type and HttpSdk.CONTENT_TYPE_HEADER_NAME not in context.headers:
                context.headers[HttpSdk.CONTENT_TYPE_HEADER_NAME] = content_type
        else:
            body = None

        authentication_instances = context.authentication_instances
        for auth_obj in authentication_instances:
            context = auth_obj.apply_authentication(context)

        url = "%s%s" % (context.host, context.url_path)
        if context.query_params is not None:
            url += "?%s" % (urlencode(context.query_params))

        log_print_request(context.method, url, context.query_params, context.headers, body)
        r = HttpSdk.get_pool_manager(context.proxy).request(
            context.method, url, body=body, headers=context.headers, redirect=False
        )
        log_print_response(r.status, r.data, r.headers)
        r = context.response_class(r)
        return r
Пример #5
0
def generate_url(scheme=None, host=None, port=None, path=None, query=None):
    """
    Generate URI from parameters.

    :param str scheme:
    :param str host:
    :param int port:
    :param str path:
    :param dict query:
    :return:
    """
    url = ""
    if scheme is not None:
        url += "%s://" % scheme
    if host is not None:
        url += host
    if port is not None:
        url += ":%s" % str(port)
    if path is not None:
        url += ensure_url_path_starts_with_slash(path)
    if query is not None:
        url += "?%s" % (urlencode(query))
    return url
Пример #6
0
def get_url_query_params(params):
    return "?%s" % (urlencode(params))