本文整理汇总了Python中six.moves.urllib_parse.quote方法的典型用法代码示例。如果您正苦于以下问题:Python urllib_parse.quote方法的具体用法?Python urllib_parse.quote怎么用?Python urllib_parse.quote使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.urllib_parse
的用法示例。
在下文中一共展示了urllib_parse.quote方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _show_endpoints
# 需要导入模块: from six.moves import urllib_parse [as 别名]
# 或者: from six.moves.urllib_parse import quote [as 别名]
def _show_endpoints(apis, pattern, endpoint, proto):
"""Show cell endpoints."""
url = '/endpoint/%s' % urllib_parse.quote(pattern)
if endpoint:
if proto:
url += '/' + proto
else:
url += '/*'
url += '/' + endpoint
response = restclient.get(apis, url)
endpoints = [{
'name': end['name'],
'proto': end['proto'],
'endpoint': end['endpoint'],
'hostport': '{0}:{1}'.format(end['host'], end['port']),
'state': end.get('state')
} for end in response.json()]
cli.out(_ENDPOINT_FORMATTER(endpoints))
示例2: get
# 需要导入模块: from six.moves import urllib_parse [as 别名]
# 或者: from six.moves.urllib_parse import quote [as 别名]
def get(self, *args, **kwargs):
if not settings.PROJECT:
return Response('Project name is not set', status=HTTP_400_BAD_REQUEST)
if not settings.TOKEN:
return Response('Project token is not set', status=HTTP_400_BAD_REQUEST)
token = self.request.get_argument('token', '')
install_type = self.request.get_argument('install_type', '')
if settings.WEB_BASE_URL.startswith('https') and not self.request.full_url().startswith('https'):
web_base_url = 'http{}'.format(settings.WEB_BASE_URL[5:])
else:
web_base_url = settings.WEB_BASE_URL
if token:
url = '{}/projects/register/{}'.format(web_base_url, token)
else:
url = '{}/projects/register'.format(web_base_url)
parameters = [
['project', settings.PROJECT],
['referrer', self.request.full_url().encode('utf8')],
]
if install_type:
parameters.append(['install_type', install_type])
query_string = '&'.join(map(lambda x: '{}={}'.format(x[0], quote(x[1])), parameters))
return RedirectResponse('%s?%s' % (url, query_string))
示例3: get_media_url
# 需要导入模块: from six.moves import urllib_parse [as 别名]
# 或者: from six.moves.urllib_parse import quote [as 别名]
def get_media_url(self, host, media_id):
web_url = self.get_url(host, media_id)
headers = {'User-Agent': common.FF_USER_AGENT, 'Referer': web_url}
download_serv = json.loads(self.net.http_GET('https://apiv2.' + host + '/getServer?c=' + media_id, headers=headers).content)
if (download_serv['status'] == 'ok'):
download_url = json.loads(self.net.http_GET('https://' + download_serv['data']['server'] + '.' + host + '/getUpload?c=' + media_id, headers=headers).content)
sources = []
if(download_url['data']['files']):
for file_index in download_url['data']['files']:
url = urllib_parse.quote(download_url['data']['files'][file_index]['link'], ':/')
size = download_url['data']['files'][file_index]['size']
sources += [(size, url)]
return helpers.pick_source(sources, False)
raise ResolverError('Unable to locate video')
示例4: __handle_escape
# 需要导入模块: from six.moves import urllib_parse [as 别名]
# 或者: from six.moves.urllib_parse import quote [as 别名]
def __handle_escape(self, key):
while True:
start_js = self.js
offset = self.js.find(key) + len(key)
if self.js[offset] == '(' and self.js[offset + 2] == ')':
c = self.js[offset + 1]
self.js = self.js.replace('%s(%s)' % (key, c), urllib_parse.quote(c))
if start_js == self.js:
break
示例5: quote_base_url
# 需要导入模块: from six.moves import urllib_parse [as 别名]
# 或者: from six.moves.urllib_parse import quote [as 别名]
def quote_base_url(base_url):
if isinstance(base_url, unicode):
return quote(base_url.encode('utf-8'))
return quote(base_url)
示例6: parse
# 需要导入模块: from six.moves import urllib_parse [as 别名]
# 或者: from six.moves.urllib_parse import quote [as 别名]
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_base_url(src.url) if src.url else src.url
while True:
try:
fp = replace_invalid_ncr(stream)
# fp is a Unicode stream
# The lxml FAQ tells us that it is inefficient to do this
# http://lxml.de/FAQ.html#can-lxml-parse-from-file-objects-opened-in-unicode-text-mode
# but actually it seems just fine as long as you tell the parser to use 'utf-8'!?
parser = HTMLParser(encoding='utf-8')
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
示例7: urlquote
# 需要导入模块: from six.moves import urllib_parse [as 别名]
# 或者: from six.moves.urllib_parse import quote [as 别名]
def urlquote(name, *args, **kwargs):
if isinstance(name, unicode):
name = name.encode('utf-8')
return urllib.quote(name, *args, **kwargs)
示例8: test_script_version_url_with_spaces
# 需要导入模块: from six.moves import urllib_parse [as 别名]
# 或者: from six.moves.urllib_parse import quote [as 别名]
def test_script_version_url_with_spaces(self):
# Handles https://github.com/wooey/Wooey/issues/290
script_version = self.choice_script
spaced_version = 'v 1 0 0'
script_version.script_version = spaced_version
script_version.save()
url = script_version.get_version_url()
self.assertIn(quote(spaced_version), url)
示例9: _ConvertIdToHeader
# 需要导入模块: from six.moves import urllib_parse [as 别名]
# 或者: from six.moves.urllib_parse import quote [as 别名]
def _ConvertIdToHeader(self, request_id):
"""Convert an id to a Content-ID header value.
Args:
request_id: String identifier for a individual request.
Returns:
A Content-ID header with the id_ encoded into it. A UUID is
prepended to the value because Content-ID headers are
supposed to be universally unique.
"""
return '<%s+%s>' % (self.__base_id, urllib_parse.quote(request_id))
示例10: testQueryEncoding
# 需要导入模块: from six.moves import urllib_parse [as 别名]
# 或者: from six.moves.urllib_parse import quote [as 别名]
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))
示例11: encode_uri_parts
# 需要导入模块: from six.moves import urllib_parse [as 别名]
# 或者: from six.moves.urllib_parse import quote [as 别名]
def encode_uri_parts(path):
"""Encode URI path components"""
return '/'.join([urllib_parse.quote(part) for part in path.split('/')])
示例12: _health_check
# 需要导入模块: from six.moves import urllib_parse [as 别名]
# 或者: from six.moves.urllib_parse import quote [as 别名]
def _health_check(pattern, proto, endpoint, command):
"""Invoke instance health check."""
stateapi = context.GLOBAL.state_api()
stateurl = '/endpoint/%s/%s/%s' % (urllib_parse.quote(pattern),
proto,
endpoint)
response = restclient.get(stateapi, stateurl)
lines = [
'%s %s' % (end['name'], '%s:%s' % (end['host'], end['port']))
for end in response.json()
]
cmd_input = '\n'.join(lines)
bad = []
try:
proc = subprocess.Popen(
command,
close_fds=_CLOSE_FDS, shell=False,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
)
(out, _err) = proc.communicate(cmd_input.encode())
retcode = proc.returncode
if proc.returncode == 0:
for instance in out.decode().splitlines():
_LOGGER.info('not ok: %s', instance)
bad.append(instance)
else:
_LOGGER.warning('Health check ignored. %r, rc: %s.',
command, retcode)
except Exception: # pylint: disable=W0703
_LOGGER.exception('Error invoking: %r', command)
return bad
示例13: inject
# 需要导入模块: from six.moves import urllib_parse [as 别名]
# 或者: from six.moves.urllib_parse import quote [as 别名]
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
示例14: init
# 需要导入模块: from six.moves import urllib_parse [as 别名]
# 或者: from six.moves.urllib_parse import quote [as 别名]
def init():
"""Return top level command handler."""
@click.command()
@click.option('--cell', required=True,
envvar='TREADMILL_CELL',
callback=cli.handle_context_opt,
expose_value=False)
@click.option('--wait', help='Wait until the app starts up',
is_flag=True, default=False)
@click.option('--ssh', help='SSH client to use.',
type=click.Path(exists=True, readable=True))
@click.argument('app')
@click.argument('command', nargs=-1)
def ssh(ssh, app, command, wait):
"""SSH into Treadmill container."""
if ssh is None:
ssh = _DEFAULT_SSH
if wait:
_wait_for_app(ssh, app, command)
else:
apis = context.GLOBAL.state_api()
url = '/endpoint/{}/tcp/ssh'.format(urllib_parse.quote(app))
response = restclient.get(apis, url)
endpoints = response.json()
_LOGGER.debug('endpoints: %r', endpoints)
if not endpoints:
cli.bad_exit('No ssh endpoint(s) found for %s', app)
# Take the first one, if there are more than one, then this is
# consistent with when 1 is returned.
endpoint = endpoints[0]
run_ssh(
endpoint['host'],
str(endpoint['port']), ssh, list(command)
)
return ssh
示例15: init
# 需要导入模块: from six.moves import urllib_parse [as 别名]
# 或者: from six.moves.urllib_parse import quote [as 别名]
def init():
"""Return top level command handler."""
@click.command()
@click.option('--cell',
callback=cli.handle_context_opt,
envvar='TREADMILL_CELL',
expose_value=False,
required=True)
@click.argument('app-or-svc')
@click.option('--host',
help='Hostname where to look for the logs',
required=True)
@click.option('--uniq',
help='The container uniq id',
required=False)
@click.option('--service',
help='The name of the service for which the logs are '
'to be retreived',
required=False)
def logs(app_or_svc, host, uniq, service):
"""View application's service logs."""
try:
app, uniq, logtype, logname = app_or_svc.split('/', 3)
except ValueError:
app, uniq, logtype, logname = app_or_svc, uniq, 'service', service
if any(param is None for param in [app, uniq, logtype, logname]):
cli.bad_exit('Incomplete parameter list')
_host, port = _nodeinfo_endpoint(host)
if not port:
cli.bad_exit('Unable for fine nodeinfo endpoint.')
api = 'http://{0}:{1}'.format(host, port)
logurl = '/local-app/%s/%s/%s/%s' % (
urllib_parse.quote(app),
urllib_parse.quote(uniq),
logtype,
urllib_parse.quote(logname)
)
log = restclient.get(api, logurl)
click.echo(log.text)
return logs