Python parse.ParseResult方法代码示例

本文整理汇总了Python中urllib.parse.ParseResult方法的典型用法代码示例。如果您正苦于以下问题:Python parse.ParseResult方法的具体用法?Python parse.ParseResult怎么用?Python parse.ParseResult使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块urllib.parse的用法示例。

在下文中一共展示了parse.ParseResult方法的25个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: urlparams

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def urlparams(url_, hash=None, **query):
    """Add a fragment and/or query paramaters to a URL.
    New query params will be appended to exising parameters, except duplicate
    names, which will be replaced.
    """
    url = urlparse.urlparse(url_)
    fragment = hash if hash is not None else url.fragment
    # Use dict(parse_qsl) so we don't get lists of values.
    query_dict = dict(urlparse.parse_qsl(url.query))
    query_dict.update(query)
    query_string = urlencode(
        [(k, v) for k, v in query_dict.items() if v is not None])
    new = urlparse.ParseResult(url.scheme, url.netloc, url.path, url.params,
                               query_string, fragment)
    return new.geturl() 
开发者ID:mozilla,项目名称:sugardough,代码行数:20,代码来源:helpers.py


示例2: url_to_string

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def url_to_string(url):
    """Convert url from ``list`` or ``ParseResult`` to string."""
    if isinstance(url, list):
        return ParseResult(
            scheme=url[0],
            netloc=url[1],
            path=url[2],
            params=None,
            query=None,
            fragment=None,
        ).geturl()
    if isinstance(url, ParseResult):
        return url.geturl()
    if isinstance(url, str):
        return url
    raise ValueError('url value not recognized') 
开发者ID:SwissDataScienceCenter,项目名称:renku-python,代码行数:21,代码来源:urls.py


示例3: get_logo_url

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def get_logo_url(base_url, logo_file):
    base_url = parse.urlparse(base_url)
    netloc = base_url.netloc
    if base_url.netloc.startswith('localhost'):
        netloc = 'notify.tools'
    elif base_url.netloc.startswith('www'):
        # strip "www."
        netloc = base_url.netloc[4:]
    logo_url = parse.ParseResult(
        scheme=base_url.scheme,
        netloc='static-logos.' + netloc,
        path=logo_file,
        params=base_url.params,
        query=base_url.query,
        fragment=base_url.fragment
    )
    return parse.urlunparse(logo_url) 
开发者ID:alphagov,项目名称:notifications-api,代码行数:21,代码来源:send_to_providers.py


示例4: _uri_sort_query

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def _uri_sort_query(cls, uri_parsed: UrlParseResult) -> UrlParseResult:
        if uri_parsed.query == '':
            return uri_parsed
        query_dict = parse_qs(uri_parsed.query, keep_blank_values=True)
        if 'variables' not in query_dict:
            return uri_parsed
        variables = query_dict['variables'][0]
        variables_dict = json_loads(variables)
        variables_dict_sorted = OrderedDict((k, variables_dict[k]) for k in sorted(variables_dict))
        query_dict['variables'][0] = json_dumps(variables_dict_sorted)
        query_sorted = urlencode(query_dict, doseq=True)
        return super()._uri_sort_query(UrlParseResult(
            uri_parsed.scheme,
            uri_parsed.netloc,
            uri_parsed.path,
            uri_parsed.params,
            query_sorted,
            uri_parsed.fragment
        )) 
开发者ID:k4cg,项目名称:nichtparasoup,代码行数:21,代码来源:test_instagram.py


示例5: geturl

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def geturl(self, include_params=True):
        params = self.params
        query = self.query
        fragment = self.fragment
        if not include_params:
            params = ""
            query = ""
            fragment = ""
        r = ParseResult(scheme=self.scheme,
                        netloc=self.netloc,
                        path=self.path,
                        params=params,
                        query=query,
                        fragment=fragment)
        return r.geturl() 
开发者ID:roglew,项目名称:pappy-proxy,代码行数:19,代码来源:proxy.py


示例6: s3_exists

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def s3_exists(url: ParseResult) -> bool:
    """Return is an S3 resource exists.
    Parameters
    ----------
    url: ParseResult
        The parsed URL.
    Returns
    -------
    bool
        True if it exists. False otherwise.
    """
    s3 = boto3.resource('s3')
    try:
        bucket = s3.Bucket(url.netloc)
        path = url.path[1:]  # Not consider starting '/'
        objs = list(bucket.objects.filter(Prefix=path))
        return len(objs) > 0
    except s3.meta.client.exceptions.NoSuchBucket:
        return False 
开发者ID:asappresearch,项目名称:flambe,代码行数:24,代码来源:downloader.py


示例7: s3_remote_file

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def s3_remote_file(url: ParseResult) -> bool:
    """Check if an existing S3 hosted artifact is a file or a folder.
    Parameters
    ----------
    url: ParseResult
        The parsed URL.
    Returns
    -------
    bool
        True if it's a file, False if it's a folder.
    """
    s3 = boto3.resource('s3')
    bucket = s3.Bucket(url.netloc)
    path = url.path[1:]  # Not consider starting '/'
    objs = list(bucket.objects.filter(Prefix=path))
    if len(objs) == 1 and objs[0].key == path:
        return True
    return False 
开发者ID:asappresearch,项目名称:flambe,代码行数:24,代码来源:downloader.py


示例8: build_request

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def build_request(self, path=None, headers=None, endpoint=None):
        headers = {} if headers is None else headers
        if endpoint is None:
            endpoint = self._endpoint
        if path is None:
            url = endpoint
        else:
            p = urlparse.urlparse(endpoint)
            # should not use `os.path.join` since it returns path string like "/foo\\bar"
            request_path = path if p.path == "/" else "/".join([p.path, path])
            url = urlparse.urlunparse(
                urlparse.ParseResult(
                    p.scheme, p.netloc, request_path, p.params, p.query, p.fragment
                )
            )
        # use default headers first
        _headers = dict(self._headers)
        # add default headers
        _headers["authorization"] = "TD1 %s" % (self._apikey,)
        _headers["date"] = email.utils.formatdate(time.time())
        _headers["user-agent"] = self._user_agent
        # override given headers
        _headers.update({key.lower(): value for (key, value) in headers.items()})
        return (url, _headers) 
开发者ID:treasure-data,项目名称:td-client-python,代码行数:26,代码来源:api.py


示例9: fetch_api_description

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def fetch_api_description(
    url: typing.Union[str, ParseResult, SplitResult], insecure: bool = False
):
    """Fetch the API description from the remote MAAS instance."""
    url_describe = urljoin(_ensure_url_string(url), "describe/")
    connector = aiohttp.TCPConnector(verify_ssl=(not insecure))
    session = aiohttp.ClientSession(connector=connector)
    async with session, session.get(url_describe) as response:
        if response.status != HTTPStatus.OK:
            raise RemoteError("{0} -> {1.status} {1.reason}".format(url, response))
        elif response.content_type != "application/json":
            raise RemoteError(
                "Expected application/json, got: %s" % response.content_type
            )
        else:
            return await response.json() 
开发者ID:maas,项目名称:python-libmaas,代码行数:18,代码来源:helpers.py


示例10: __init__

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def __init__(self, urlobj: ParseResult):
        self.kind = 'http'
        host = urlobj.hostname
        if urlobj.port:
            host += ':{}'.format(urlobj.port)
        self.url = '{}://{}{}'.format(urlobj.scheme, host, urlobj.path)
        if urlobj.username or urlobj.password:
            self.auth = (urlobj.username, urlobj.password)
            self.nuclio_header = basic_auth_header(urlobj.username,
                                                   urlobj.password)
        else:
            self.auth = None
            self.nuclio_header = None
        self.path = urlobj.path
        self.workdir = urlobj.fragment 
开发者ID:nuclio,项目名称:nuclio-jupyter,代码行数:18,代码来源:archive.py


示例11: dispatch

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def dispatch(self, request, *args, **kwargs):
        if not self.test_func_tou_required(request.user):
            messages.add_message(
                request,
                messages.INFO,
                "You need to agree to the terms of use before you can do that.",
            )
            # Remember where they were trying to go, so we can redirect them
            # back after they agree. There's logic in TermsView to pick up on
            # this parameter.
            next_path = request.path
            next_param = urlencode({REDIRECT_FIELD_NAME: next_path})
            path = reverse_lazy("terms")
            new_url = ParseResult(
                scheme="",
                netloc="",
                path=str(path),
                params="",
                query=str(next_param),
                fragment="",
            ).geturl()
            return HttpResponseRedirect(new_url)
        return super(ToURequired, self).dispatch(request, *args, **kwargs) 
开发者ID:WikipediaLibrary,项目名称:TWLight,代码行数:27,代码来源:view_mixins.py


示例12: get_payable_from_BIP21URI

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def get_payable_from_BIP21URI(uri: str, proto: str = "bitcoin") -> Tuple[str, Decimal]:
    """ Computes a 'payable' tuple from a given BIP21 encoded URI.
    :param uri: The BIP21 URI to decode
    :param proto: The expected protocol/scheme (case insensitive)
    :returns: A payable (address, amount) corresponding to the given URI
    :raise: Raises s ValueError if there is no address given or if the
        protocol/scheme doesn't match what is expected
    """
    obj = parse.urlparse(uri)  # type: parse.ParseResult
    if not obj.path or obj.scheme.upper() != proto.upper():
        raise ValueError("Malformed URI")
    if not obj.query:
        return obj.path, None
    query = parse.parse_qs(obj.query)  # type: Dict
    return obj.path, Decimal(query["amount"][0]) 
开发者ID:metamarcdw,项目名称:nowallet,代码行数:18,代码来源:nowallet.py


示例13: get_direct_url

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def get_direct_url(url, headers):
    """Gets the zip direct download link from the project download page"""
    direct_download_url = href_from_link_text(url,
                                              headers,
                                              'Problems Downloading')
    parsed_download_url = urlparse(direct_download_url)
    if parsed_download_url.scheme not in ['http', 'https']:
        # url is relative, and is missing the scheme and netloc
        parsed_parent_url = urlparse(url)
        parsed_download_url = ParseResult(parsed_parent_url.scheme,
                                          parsed_parent_url.netloc,
                                          parsed_download_url.path,
                                          parsed_download_url.params,
                                          parsed_download_url.query,
                                          parsed_download_url.fragment)
        direct_download_url = parsed_download_url.geturl()
    direct_download_url = href_from_link_text(direct_download_url,
                                              headers,
                                              'direct link')
    return direct_download_url 
开发者ID:spacether,项目名称:pycalculix,代码行数:22,代码来源:installer.py


示例14: __init__

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def __init__(self, system_ids, sources, proxy=None):
        """Create a new importer.
        :param system_ids: A sequence of rack controller system_id's.
        :param sources: A sequence of endpoints; see `ImportBootImages`.
        :param proxy: The HTTP/HTTPS proxy to use, or `None`
        :type proxy: :class:`urlparse.ParseResult` or string
        """
        super().__init__()
        self.system_ids = tuple(flatten(system_ids))
        if isinstance(sources, Sequence):
            self.sources = sources
        else:
            raise TypeError("expected sequence, got: %r" % (sources,))
        if proxy is None or isinstance(proxy, ParseResult):
            self.proxy = proxy
        else:
            self.proxy = urlparse(proxy) 
开发者ID:maas,项目名称:maas,代码行数:20,代码来源:boot_images.py


示例15: base_url

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def base_url(self) -> str:
        """Returns the base url without query string or fragments."""
        return urlunparse(ParseResult(self.scheme, self.host, self.path, "", "", "")) 
开发者ID:pgjones,项目名称:quart,代码行数:5,代码来源:base.py


示例16: host_url

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def host_url(self) -> str:
        return urlunparse(ParseResult(self.scheme, self.host, "", "", "", "")) 
开发者ID:pgjones,项目名称:quart,代码行数:4,代码来源:base.py


示例17: url

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def url(self) -> str:
        """Returns the full url requested."""
        return urlunparse(
            ParseResult(
                self.scheme, self.host, self.path, "", self.query_string.decode("ascii"), ""
            )
        ) 
开发者ID:pgjones,项目名称:quart,代码行数:9,代码来源:base.py


示例18: url_root

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def url_root(self) -> str:
        return urlunparse(
            ParseResult(self.scheme, self.host, self.path.rsplit("/", 1)[0] + "/", "", "", "")
        ) 
开发者ID:pgjones,项目名称:quart,代码行数:6,代码来源:base.py


示例19: _try_parse_url

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def _try_parse_url(url: str) -> Tuple[ParseResult, bool]:
        try:
            result = urlparse(url)
            return result, True
        except ValueError:
            return None, False 
开发者ID:microsoft,项目名称:botbuilder-python,代码行数:8,代码来源:luis_application.py


示例20: get_remote_connection_headers

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def get_remote_connection_headers(cls, parsed_url: 'ParseResult', keep_alive: bool = True) -> Dict[str, Any]:
        """Override get_remote_connection_headers in RemoteConnection"""
        headers = RemoteConnection.get_remote_connection_headers(parsed_url, keep_alive=keep_alive)
        headers['User-Agent'] = 'appium/python {} ({})'.format(library_version(), headers['User-Agent'])
        if parsed_url.path.endswith('/session'):
            # https://github.com/appium/appium-base-driver/pull/400
            headers['X-Idempotency-Key'] = str(uuid.uuid4())
        return headers 
开发者ID:appium,项目名称:python-client,代码行数:11,代码来源:appium_connection.py


示例21: get_callback_url

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def get_callback_url(self):
    from urllib.parse import urlparse, ParseResult
    import urllib.request, urllib.parse, urllib.error
    callback_url_parse = urlparse(self.callback)
    query_args = {
      'fwd_fee'               : self.fwd_miners_fee or 0,
      'input_fee'             : self.input_miners_fee or 0,
      'value'                 : self.value,
      'input_address'         : self.input_address,
      'confirmations'         : self.confirmations,
      'transaction_hash'      : self.transaction_hash,
      'input_transaction_hash': self.input_transaction_hash,
      'destination_address'   : self.destination_address,
      'payee_addresses'       : self.payee_addresses
    }
    if not callback_url_parse.query:
      url_query = urllib.parse.urlencode(query_args)
    else:
      url_query = callback_url_parse.query + '&' + urllib.parse.urlencode(query_args)
    callback_url = ParseResult(scheme=callback_url_parse.scheme ,
                               netloc=callback_url_parse.netloc,
                               path=callback_url_parse.path,
                               params=callback_url_parse.params,
                               query= url_query,
                               fragment=callback_url_parse.fragment).geturl()
    return callback_url 
开发者ID:bitex-coin,项目名称:backend,代码行数:32,代码来源:models.py


示例22: parse_url

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def parse_url(v):
    # type: (str) -> ParseResult
    value = urlparse(v)
    if value.scheme not in ("http", "https"):
        raise ValueError(
            f"Invalid URL scheme {value.scheme}. " f"Only HTTP(s) URLs are allowed"
        )
    value.port
    return value 
开发者ID:matrix-org,项目名称:pantalaimon,代码行数:13,代码来源:config.py


示例23: add_url_params

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def add_url_params(url, params):
    """ Add GET params to provided URL being aware of existing.
    :param url: string of target URL
    :param params: dict containing requested params to be added
    :return: string with updated URL
    >> url = 'http://stackoverflow.com/test?answers=true'
    >> new_params = {'answers': False, 'data': ['some','values']}
    >> add_url_params(url, new_params)
    'http://stackoverflow.com/test?data=some&data=values&answers=false'
    """
    # Unquoting URL first so we don't loose existing args
    url = unquote(url)
    # Extracting url info
    parsed_url = urlparse(url)
    # Extracting URL arguments from parsed URL
    get_args = parsed_url.query
    # Converting URL arguments to dict
    parsed_get_args = dict(parse_qsl(get_args))
    # Merging URL arguments dict with new params
    parsed_get_args.update(params)
    # Bool and Dict values should be converted to json-friendly values
    # you may throw this part away if you don't like it :)
    parsed_get_args.update(
        {k: dumps(v) for k, v in parsed_get_args.items()
         if isinstance(v, (bool, dict))}
    )
    # Converting URL argument to proper query string
    encoded_get_args = urlencode(parsed_get_args, doseq=True)
    # Creating new parsed result object based on provided with new
    # URL arguments. Same thing happens inside of urlparse.
    new_url = ParseResult(
        parsed_url.scheme, parsed_url.netloc, parsed_url.path,
        parsed_url.params, encoded_get_args, parsed_url.fragment
    ).geturl()
    return new_url 
开发者ID:Tribler,项目名称:py-ipv8,代码行数:42,代码来源:encoding.py


示例24: _serialize

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def _serialize(self, value: ParseResult, *args, **kwargs) -> str:
        return value.geturl()
    # Override deserialize rather than _deserialize because we need
    # to call urlparse *after* validation has occurred 
开发者ID:sloria,项目名称:environs,代码行数:7,代码来源:__init__.py


示例25: deserialize

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import ParseResult [as 别名]
def deserialize(self, value: str, attr: str = None, data: typing.Mapping = None, **kwargs) -> ParseResult:
        ret = super().deserialize(value, attr, data, **kwargs)
        return urlparse(ret) 
开发者ID:sloria,项目名称:environs,代码行数:5,代码来源:__init__.py



注:本文中的urllib.parse.ParseResult方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。