Python six.moves.urllib_parse.quote() Examples
The following are 17
code examples of six.moves.urllib_parse.quote().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
six.moves.urllib_parse
, or try the search function
.
Example #1
Source File: show.py From treadmill with Apache License 2.0 | 6 votes |
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))
Example #2
Source File: test_models.py From Wooey with BSD 3-Clause "New" or "Revised" License | 5 votes |
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)
Example #3
Source File: codecs.py From jaeger-client-python with Apache License 2.0 | 5 votes |
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
Example #4
Source File: reaper.py From treadmill with Apache License 2.0 | 5 votes |
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
Example #5
Source File: utils.py From treadmill with Apache License 2.0 | 5 votes |
def encode_uri_parts(path): """Encode URI path components""" return '/'.join([urllib_parse.quote(part) for part in path.split('/')])
Example #6
Source File: base_api_test.py From apitools with Apache License 2.0 | 5 votes |
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))
Example #7
Source File: batch.py From apitools with Apache License 2.0 | 5 votes |
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))
Example #8
Source File: register.py From jet-bridge with MIT License | 5 votes |
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))
Example #9
Source File: jsunfuck.py From script.module.resolveurl with GNU General Public License v2.0 | 5 votes |
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
Example #10
Source File: gofile.py From script.module.resolveurl with GNU General Public License v2.0 | 5 votes |
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')
Example #11
Source File: py2compat.py From wextracto with BSD 3-Clause "New" or "Revised" License | 5 votes |
def urlquote(name, *args, **kwargs): if isinstance(name, unicode): name = name.encode('utf-8') return urllib.quote(name, *args, **kwargs)
Example #12
Source File: etree.py From wextracto with BSD 3-Clause "New" or "Revised" License | 5 votes |
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
Example #13
Source File: etree.py From wextracto with BSD 3-Clause "New" or "Revised" License | 5 votes |
def quote_base_url(base_url): if isinstance(base_url, unicode): return quote(base_url.encode('utf-8')) return quote(base_url)
Example #14
Source File: jsunfuck.py From script.module.urlresolver with GNU General Public License v2.0 | 5 votes |
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
Example #15
Source File: gofile.py From script.module.urlresolver with GNU General Public License v2.0 | 5 votes |
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')
Example #16
Source File: ssh.py From treadmill with Apache License 2.0 | 4 votes |
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
Example #17
Source File: logs.py From treadmill with Apache License 2.0 | 4 votes |
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