• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python urllib_parse.quote函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中six.moves.urllib_parse.quote函数的典型用法代码示例。如果您正苦于以下问题:Python quote函数的具体用法?Python quote怎么用?Python quote使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: inject

 def inject(self, span_context, carrier):
     if not isinstance(carrier, dict):
         raise InvalidCarrierException('carrier not a collection')
     # Note: we do not url-encode the trace ID because the ':' separator
     # is not a problem for HTTP header values
     carrier[self.trace_id_header] = span_context_to_string(
         trace_id=span_context.trace_id, span_id=span_context.span_id,
         parent_id=span_context.parent_id, flags=span_context.flags)
     baggage = span_context.baggage
     if baggage:
         for key, value in six.iteritems(baggage):
             encoded_key = key
             if self.url_encoding:
                 if six.PY2 and isinstance(value, six.text_type):
                     encoded_value = urllib_parse.quote(value.encode('utf-8'))
                 else:
                     encoded_value = urllib_parse.quote(value)
                 # we assume that self.url_encoding means we are injecting
                 # into HTTP headers. httplib does not like unicode strings
                 # so we convert the key to utf-8. The URL-encoded value is
                 # already a plain string.
                 if six.PY2 and isinstance(key, six.text_type):
                     encoded_key = key.encode('utf-8')
             else:
                 if six.PY3 and isinstance(value, six.binary_type):
                     encoded_value = str(value, 'utf-8')
                 else:
                     encoded_value = value
             if six.PY3 and isinstance(key, six.binary_type):
                 encoded_key = str(key, 'utf-8')
             # Leave the below print(), you will thank me next time you debug unicode strings
             # print('adding baggage', key, '=>', value, 'as', encoded_key, '=>', encoded_value)
             header_key = '%s%s' % (self.baggage_prefix, encoded_key)
             carrier[header_key] = encoded_value
开发者ID:uber,项目名称:jaeger-client-python,代码行数:34,代码来源:codecs.py


示例2: reconstruct_url

def reconstruct_url(environ):
	secure = environ['wsgi.url_scheme'] == 'https'
	if secure:
		url = 'wss://'
	else:
		url = 'ws://'

	if environ.get('HTTP_HOST'):
		url += environ['HTTP_HOST']
	else:
		url += environ['SERVER_NAME']

		if secure:
			if environ['SERVER_PORT'] != '443':
				url += ':' + environ['SERVER_PORT']
		else:
			if environ['SERVER_PORT'] != '80':
				url += ':' + environ['SERVER_PORT']

	url += quote(environ.get('SCRIPT_NAME', ''))
	url += quote(environ.get('PATH_INFO', ''))

	if environ.get('QUERY_STRING'):
		url += '?' + environ['QUERY_STRING']

	return url
开发者ID:NextThought,项目名称:nti.geventwebsocket,代码行数:26,代码来源:handler.py


示例3: test_users_request

 def test_users_request(self):
     """Create a UsersRequest"""
     t = self.create_request_object()
     self.assertEqual('datasets/Users.odm?studyoid=%s' % quote(t.studyoid),
                      t.url_path())
     t = self.create_request_object(location_oid="1002")
     self.assertTrue('locationoid=%s' % quote("1002") in t.url_path())
     self.assertTrue('studyoid=%s' % quote(t.studyoid) in t.url_path())
开发者ID:Hamoto,项目名称:rwslib,代码行数:8,代码来源:test_odm_adapter.py


示例4: test_successful_configuration

 def test_successful_configuration(self):
     """We can successfully request ProtocolDeviations"""
     t = self.create_request_object('Mediflex', 'Dev')
     self.assertEqual('datasets/SDTMDataDictionaries.csv?studyid=%s' % quote(t.studyname_environment()),
                      t.url_path())
     t = self.create_request_object('Mediflex', 'Dev', dataset_format="xml")
     self.assertEqual('datasets/SDTMDataDictionaries?studyid=%s' % quote(t.studyname_environment()),
                      t.url_path())
开发者ID:mdsol,项目名称:rwslib,代码行数:8,代码来源:test_biostats_gateway.py


示例5: _get_canonical_query

 def _get_canonical_query(self, req):
     req_params = urlparse.parse_qsl(urlparse.urlparse(req.url).query,
                                     keep_blank_values=True)
     params = []
     for key, val in sorted(req_params or []):
         params.append('='.join((urlparse.quote(key, safe='~-_.'),
                                 urlparse.quote(val, safe='~-_.'))))
     c_params = '&'.join(params)
     self.log.debug('canonical query: %s', c_params)
     return c_params
开发者ID:castedo,项目名称:requestbuilder,代码行数:10,代码来源:aws.py


示例6: generic

def generic(d):
    """Converts any dict into a URL. The domain (netlog) is always
example.org, and all keys/values of the dict is turned into a
querystring.

    >>> generic({'foo':'1', 'bar':'2'})
    "http://example.org/?foo=1&bar=2"

    """

    querystring = "&".join([quote(k) + "=" + quote(v) for (k, v) in d.items()])
    return "http://example.org/?%s" % querystring
开发者ID:h4ck3rm1k3,项目名称:ferenda,代码行数:12,代码来源:uriformats.py


示例7: get_outgoing_url

def get_outgoing_url(url):
    """
    Bounce a URL off an outgoing URL redirector, such as
    outgoing.prod.mozaws.net.
    """
    if not settings.REDIRECT_URL:
        return url

    # django.utils.http._urlparse is a copy of python's urlparse()
    # "but uses fixed urlsplit() function".
    parsed_url = django_urlparse(url)
    url_netloc = parsed_url.netloc

    # This prevents a link like javascript://addons.mozilla.org...
    # being returned unchanged since the netloc matches the
    # safe list see bug 1251023
    if parsed_url.scheme not in ['http', 'https']:
        return '/'

    # No double-escaping, and some domain names are excluded.
    if (url_netloc == django_urlparse(settings.REDIRECT_URL).netloc or
            url_netloc in settings.REDIRECT_URL_ALLOW_LIST):
        return url

    url = force_bytes(jinja2.utils.Markup(url).unescape())
    sig = hmac.new(force_bytes(settings.REDIRECT_SECRET_KEY),
                   msg=url, digestmod=hashlib.sha256).hexdigest()
    # Let '&=' through so query params aren't escaped.  We probably shouldn't
    # bother to quote the query part at all.
    return '/'.join([settings.REDIRECT_URL.rstrip('/'), sig,
                     quote(url, safe='/&=')])
开发者ID:diox,项目名称:olympia,代码行数:31,代码来源:urlresolvers.py


示例8: basefile_to_pathfrag

    def basefile_to_pathfrag(self, basefile):
        """Given a basefile, returns a string that can safely be used
        as a fragment of the path for any representation of that
        file. The default implementation recognizes a number of
        characters that are unsafe to use in file names and replaces
        them with HTTP percent-style encoding.

        Example:

        >>> d = DocumentStore("/tmp")
        >>> realsep = os.sep
        >>> os.sep = "/"
        >>> d.basefile_to_pathfrag('1998:204') == '1998/%3A204'
        True
        >>> os.sep = realsep

        If you wish to override how document files are stored in
        directories, you can override this method, but you should make
        sure to also override
        :py:meth:`~ferenda.DocumentStore.pathfrag_to_basefile` to
        work as the inverse of this method.

        :param basefile: The basefile to encode
        :type basefile: str
        :returns: The encoded path fragment
        :rtype: str
        """
        safe = '/;@&=+,'
        if sys.version_info < (2, 7, 0):
            # urllib.quote in python 2.6 cannot handle unicode values
            # for the safe parameter. FIXME: We should create a shim
            # as ferenda.compat.quote and use that
            safe = safe.encode('ascii') # pragma: no cover

        return quote(basefile, safe=safe).replace('%', os.sep + '%')
开发者ID:h4ck3rm1k3,项目名称:ferenda,代码行数:35,代码来源:documentstore.py


示例9: parse

def parse(src):
    """ Returns an element tree create by `LXML <http://lxml.de/>`_.
       :param src: A readable object such as a :class:`wex.response.Response`.
    """

    if not hasattr(src, 'read'):
        return src

    etree = _ElementTree()
    try:
        stream = HTMLStream(src)
        # Sometimes we get URLs containing characters that aren't
        # acceptable to lxml (e.g. "http:/foo.com/bar?this=array[]").
        # When this happens lxml will quote the whole URL.
        # We don't want to have to check for this so we just always
        # quote it here and then unquote it in the `base_url` function.
        quoted_base_url = quote(src.url) if src.url else src.url
        while True:
            try:
                parser = HTMLParser()
                fp = replace_invalid_ncr(stream)
                etree.parse(fp, parser=parser, base_url=quoted_base_url)
                break
            except UnicodeDecodeError as exc:
                stream.next_encoding()
    except IOError as exc:
        logger = logging.getLogger(__name__)
        logger.warning("IOError parsing %s (%s)", src.url, exc)

    root = etree.getroot()
    if root is None:
        etree._setroot(UNPARSEABLE)

    return etree
开发者ID:petergao1987,项目名称:wextracto,代码行数:34,代码来源:etree.py


示例10: setup

    def setup(self, api_map=None, **kwargs):
        """
        Set up the url with required parameters and method of the request

        Params:
            `api_map`: Dict with urls and methods for the request
            `kwargs`: Optional additional parameters to be attached to the url
        """

        if api_map is None:
            raise Exception('Resolve must be called with `api_map` argument')
        elif api_map.get('url') is None or api_map.get('method') is None:
            raise Exception('Resolve must be called with a map with `url` and `method`')

        url = api_map['url']
        method = api_map['method']

        try:
            url = url.format(**kwargs)
        except KeyError as ke:
            raise exceptions.MissingParam('Missing url sdk parameter: %s' % str(ke))

        # We percent encode the url so that if any string has spaces,
        # commas or any other special character the url will be correctly formed anyway
        self.url = urllib_parse.quote(url)
        self.method = method
开发者ID:DanielMaly,项目名称:mkm-sdk,代码行数:26,代码来源:resolvers.py


示例11: _extractContentInfo

    def _extractContentInfo(self, item):
        request = self.request


        rename_ids = {}
        if "container_rename_button" in request:
            for rename_id in request.get('ids', ()):
                rename_ids[rename_id] = rename_id
        elif "rename_ids" in request:
            for rename_id in request.get('rename_ids', ()):
                rename_ids[rename_id] = rename_id


        retitle_id = request.get('retitle_id')

        id, obj = item
        info = {}
        info['id'] = info['cb_id'] = id
        info['object'] = obj

        info['url'] = urllib.quote(id.encode('utf-8'))
        info['rename'] = rename_ids.get(id)
        info['retitle'] = id == retitle_id


        zmi_icon = queryMultiAdapter((obj, self.request), name='zmi_icon')
        if zmi_icon is None:
            info['icon'] = None
        else:
            info['icon'] = zmi_icon()

        dc = IZopeDublinCore(obj, None)
        if dc is not None:
            info['retitleable'] = canWrite(dc, 'title')
            info['plaintitle'] = not info['retitleable']

            title = self.safe_getattr(dc, 'title', None)
            if title:
                info['title'] = title

            formatter = self.request.locale.dates.getFormatter(
                'dateTime', 'short')

            created = self.safe_getattr(dc, 'created', None)
            if created is not None:
                info['created'] = formatter.format(created)

            modified = self.safe_getattr(dc, 'modified', None)
            if modified is not None:
                info['modified'] = formatter.format(modified)
        else:
            info['retitleable'] = 0
            info['plaintitle'] = 1


        sized_adapter = ISized(obj, None)
        if sized_adapter is not None:
            info['size'] = sized_adapter
        return info
开发者ID:zopefoundation,项目名称:zope.app.container,代码行数:59,代码来源:contents.py


示例12: test_build_url_proxied

    def test_build_url_proxied(self):
        imdb_fr = Imdb(locale="en_FR", cache=False, anonymize=True, proxy_uri="http://someproxywebsite.co.uk?url={0}")
        imdb_fr.timestamp = time.mktime(datetime.date.today().timetuple())

        url = imdb_fr._build_url(path="/title/maindetails", params={"tconst": "tt1111111"})

        expected_url = "http://someproxywebsite.co.uk?url=" + quote("https://app.imdb.com/title/maindetails")
        assert url.startswith(expected_url) is True
开发者ID:engelkek,项目名称:imdb-pie,代码行数:8,代码来源:test_imdb.py


示例13: _cli_call

def _cli_call(context, name, args):
    if context.output_names:
        with context.io_manager.with_stdout() as fp:
            fp.write('Item Name: ')
            fp.write(parse.quote(name.encode('utf8')))
            fp.write('\n')
            fp.flush()
    return CLI()(context.original_main_args + args)
开发者ID:OddBloke,项目名称:swiftly,代码行数:8,代码来源:fordo.py


示例14: testQueryEncoding

    def testQueryEncoding(self):
        method_config = base_api.ApiMethodInfo(request_type_name="MessageWithTime", query_params=["timestamp"])
        service = FakeService()
        request = MessageWithTime(timestamp=datetime.datetime(2014, 10, 0o7, 12, 53, 13))
        http_request = service.PrepareHttpRequest(method_config, request)

        url_timestamp = urllib_parse.quote(request.timestamp.isoformat())
        self.assertTrue(http_request.url.endswith(url_timestamp))
开发者ID:jlowdermilk,项目名称:apitools,代码行数:8,代码来源:base_api_test.py


示例15: test_create_a_sites_metadata_request

 def test_create_a_sites_metadata_request(self):
     """Create a SitesMetadataRequest"""
     t = self.create_request_object()
     self.assertEqual('datasets/Sites.odm?studyoid=%s' % quote(t.studyoid),
                      t.url_path())
     t = self.create_request_object(project_name=None,
                                    environment_name=None)
     self.assertEqual('datasets/Sites.odm',
                      t.url_path())
开发者ID:Hamoto,项目名称:rwslib,代码行数:9,代码来源:test_odm_adapter.py


示例16: test_can_handle_non_ascii_URLs

    def test_can_handle_non_ascii_URLs(self):
        from OFS.Image import manage_addFile
        manage_addFile(self.app, 'täst', u'çöńtêñt'.encode('utf-8'))

        browser = Testing.testbrowser.Browser()
        browser.login('manager', 'manager_pass')

        browser.open('http://localhost/{}'.format(quote('täst')))
        self.assertEqual(browser.contents.decode('utf-8'), u'çöńtêñt')
开发者ID:zopefoundation,项目名称:Zope,代码行数:9,代码来源:test_WSGIPublisher.py


示例17: dirnames

 def dirnames(self):
     encoded = self.encode('utf-8')
     hexdigest = md5(encoded).hexdigest()
     names = [self.parsed.scheme, self.parsed.netloc]
     names.extend(self.parsed.path.split('/'))
     if self.parsed.query:
         names.extend(self.parsed.query.split('&'))
     names.append(hexdigest)
     return [quote(name, safe='')[:PC_NAME_MAX] for name in names]
开发者ID:justinvanwinkle,项目名称:wextracto,代码行数:9,代码来源:url.py


示例18: _delete

 def _delete(self, series_type, series_val, start, end, options):
     params = {
         'start': start.isoformat(),
         'end': end.isoformat(),
     }
     params.update(options)
     url = '/series/%s/%s/data/' % (series_type,
                                    quote(series_val, ""))
     json = self.request(url, method='DELETE', params=params)
     return json
开发者ID:ixmatus,项目名称:tempodb-python,代码行数:10,代码来源:client.py


示例19: test_create_audit_records_request

 def test_create_audit_records_request(self):
     """We can create an AuditRecordsRequest"""
     t = self.create_request_object()
     self.assertTrue('datasets/ClinicalAuditRecords.odm' in t.url_path())
     self.assertTrue('studyoid=%s' % quote(t.studyoid) in t.url_path())
     self.assertTrue('startid=1' in t.url_path())
     self.assertTrue('per_page=100' in t.url_path())
     t = self.create_request_object(startid=2569, per_page=50)
     self.assertTrue('startid=2569' in t.url_path())
     self.assertTrue('per_page=50' in t.url_path())
开发者ID:Hamoto,项目名称:rwslib,代码行数:10,代码来源:test_odm_adapter.py


示例20: delete_pending

    def delete_pending(self, **params):
        if 'person_email' not in params:
            raise ValueError("You must pass person_email")

        self._set_client(params)

        escaped_email = quote(params['person_email'])
        url = self.path % escaped_email

        return self.client.request('delete', url)
开发者ID:chosak,项目名称:delighted-python,代码行数:10,代码来源:resource.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python urllib_parse.urlencode函数代码示例发布时间:2022-05-27
下一篇:
Python urllib_parse.parse_qs函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap