query
stringlengths 9
60
| language
stringclasses 1
value | code
stringlengths 105
25.7k
| url
stringlengths 91
217
|
---|---|---|---|
encode url
|
python
|
def url_encode(url):
"""
Convert special characters using %xx escape.
:param url: str
:return: str - encoded url
"""
if isinstance(url, text_type):
url = url.encode('utf8')
return quote(url, ':/%?&=')
|
https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/utils.py#L286-L295
|
encode url
|
python
|
def _encode_params(**kw):
'''
Do url-encode parameters
>>> _encode_params(a=1, b='R&D')
'a=1&b=R%26D'
>>> _encode_params(a=u'\u4e2d\u6587', b=['A', 'B', 123])
'a=%E4%B8%AD%E6%96%87&b=A&b=B&b=123'
'''
def _encode(L, k, v):
if isinstance(v, unicode):
L.append('%s=%s' % (k, urllib.quote(v.encode('utf-8'))))
elif isinstance(v, str):
L.append('%s=%s' % (k, urllib.quote(v)))
elif isinstance(v, collections.Iterable):
for x in v:
_encode(L, k, x)
else:
L.append('%s=%s' % (k, urllib.quote(str(v))))
args = []
for k, v in kw.iteritems():
_encode(args, k, v)
return '&'.join(args)
|
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L90-L112
|
encode url
|
python
|
def url_encode_stream(obj, stream=None, charset='utf-8', encode_keys=False,
sort=False, key=None, separator='&'):
"""Like :meth:`url_encode` but writes the results to a stream
object. If the stream is `None` a generator over all encoded
pairs is returned.
.. versionadded:: 0.8
:param obj: the object to encode into a query string.
:param stream: a stream to write the encoded object into or `None` if
an iterator over the encoded pairs should be returned. In
that case the separator argument is ignored.
:param charset: the charset of the query string.
:param encode_keys: set to `True` if you have unicode keys.
:param sort: set to `True` if you want parameters to be sorted by `key`.
:param separator: the separator to be used for the pairs.
:param key: an optional function to be used for sorting. For more details
check out the :func:`sorted` documentation.
"""
gen = _url_encode_impl(obj, charset, encode_keys, sort, key)
if stream is None:
return gen
for idx, chunk in enumerate(gen):
if idx:
stream.write(separator)
stream.write(chunk)
|
https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_urls.py#L337-L362
|
encode url
|
python
|
def request_encode_url(self, method, url, fields=None, headers=None,
**urlopen_kw):
"""
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the url. This is useful for request methods like GET, HEAD, DELETE, etc.
"""
if headers is None:
headers = self.headers
extra_kw = {'headers': headers}
extra_kw.update(urlopen_kw)
if fields:
url += '?' + urlencode(fields)
return self.urlopen(method, url, **extra_kw)
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/request.py#L74-L89
|
encode url
|
python
|
def url_encode(obj, charset='utf-8', encode_keys=False, sort=False, key=None,
separator='&'):
"""URL encode a dict/`MultiDict`. If a value is `None` it will not appear
in the result string. Per default only values are encoded into the target
charset strings. If `encode_keys` is set to ``True`` unicode keys are
supported too.
If `sort` is set to `True` the items are sorted by `key` or the default
sorting algorithm.
.. versionadded:: 0.5
`sort`, `key`, and `separator` were added.
:param obj: the object to encode into a query string.
:param charset: the charset of the query string.
:param encode_keys: set to `True` if you have unicode keys.
:param sort: set to `True` if you want parameters to be sorted by `key`.
:param separator: the separator to be used for the pairs.
:param key: an optional function to be used for sorting. For more details
check out the :func:`sorted` documentation.
"""
return separator.join(_url_encode_impl(obj, charset, encode_keys, sort, key))
|
https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_urls.py#L313-L334
|
encode url
|
python
|
def _encode_params(**kw):
'''
do url-encode parameters
>>> _encode_params(a=1, b='R&D')
'a=1&b=R%26D'
>>> _encode_params(a=u'\u4e2d\u6587', b=['A', 'B', 123])
'a=%E4%B8%AD%E6%96%87&b=A&b=B&b=123'
'''
args = []
for k, v in kw.iteritems():
if isinstance(v, basestring):
qv = v.encode('utf-8') if isinstance(v, unicode) else v
args.append('%s=%s' % (k, urllib.quote(qv)))
elif isinstance(v, collections.Iterable):
for i in v:
qv = i.encode('utf-8') if isinstance(i, unicode) else str(i)
args.append('%s=%s' % (k, urllib.quote(qv)))
else:
qv = str(v)
args.append('%s=%s' % (k, urllib.quote(qv)))
return '&'.join(args)
|
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/weibo.py#L71-L92
|
encode url
|
python
|
def _encode_ids(*args):
"""
Do url-encode resource ids
"""
ids = []
for v in args:
if isinstance(v, basestring):
qv = v.encode('utf-8') if isinstance(v, unicode) else v
ids.append(urllib.quote(qv))
else:
qv = str(v)
ids.append(urllib.quote(qv))
return ';'.join(ids)
|
https://github.com/stevenc81/octopie/blob/4e06fd8600c8cf4337ee21cc50e748bbf760a0ba/octopie/api.py#L51-L65
|
encode url
|
python
|
def request_encode_url(self, method, url, fields=None, **urlopen_kw):
"""
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the url. This is useful for request methods like GET, HEAD, DELETE, etc.
"""
if fields:
url += '?' + urlencode(fields)
return self.urlopen(method, url, **urlopen_kw)
|
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/request.py#L74-L81
|
encode url
|
python
|
def _urlencode(items):
"""A Unicode-safe URLencoder."""
try:
return urllib.urlencode(items)
except UnicodeEncodeError:
return urllib.urlencode([(k, smart_str(v)) for k, v in items])
|
https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/helpers.py#L55-L60
|
encode url
|
python
|
def do_urlencode(value):
"""Escape strings for use in URLs (uses UTF-8 encoding). It accepts both
dictionaries and regular strings as well as pairwise iterables.
.. versionadded:: 2.7
"""
itemiter = None
if isinstance(value, dict):
itemiter = iteritems(value)
elif not isinstance(value, string_types):
try:
itemiter = iter(value)
except TypeError:
pass
if itemiter is None:
return unicode_urlencode(value)
return u'&'.join(unicode_urlencode(k) + '=' +
unicode_urlencode(v, for_qs=True)
for k, v in itemiter)
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L94-L112
|
encode url
|
python
|
def from_urlencode(self, data, options=None):
""" handles basic formencoded url posts """
qs = dict((k, v if len(v) > 1 else v[0])
for k, v in urlparse.parse_qs(data).iteritems())
return qs
|
https://github.com/westerncapelabs/django-snappy-vumi-bouncer/blob/5750827020aa83f0f5eecee87a2fe8f19dfaac16/snappybouncer/api.py#L94-L98
|
encode url
|
python
|
def urlencode(txt):
"""Url encode a path."""
if isinstance(txt, unicode):
txt = txt.encode('utf-8')
return urllib.quote_plus(txt)
|
https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/helpers.py#L64-L68
|
encode url
|
python
|
def encode(url):
"""Encode URL."""
parts = extract(url)
return construct(URL(parts.scheme,
parts.username,
parts.password,
_idna_encode(parts.subdomain),
_idna_encode(parts.domain),
_idna_encode(parts.tld),
parts.port,
quote(parts.path.encode('utf-8')),
_encode_query(parts.query),
quote(parts.fragment.encode('utf-8')),
None))
|
https://github.com/rbaier/python-urltools/blob/76bf599aeb4cb463df8e38367aa40a7d8ec7d9a1/urltools/urltools.py#L134-L147
|
encode url
|
python
|
def urlencode(query):
"""Encode string to be used in urls (percent encoding).
:param query: string to be encoded
:type query: str
:return: urlencoded string
:rtype: str
:Example:
>>> urlencode('pekná líščička')
'pekn%C3%A1%20l%C3%AD%C5%A1%C4%8Di%C4%8Dka'
"""
if hasattr(urllib, 'parse'):
return urllib.parse.urlencode(query)
else:
return urllib.urlencode(query)
|
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/url_helper.py#L42-L57
|
encode url
|
python
|
def _encode_auth(auth):
"""
A function compatible with Python 2.3-3.3 that will encode
auth from a URL suitable for an HTTP header.
>>> str(_encode_auth('username%3Apassword'))
'dXNlcm5hbWU6cGFzc3dvcmQ='
Long auth strings should not cause a newline to be inserted.
>>> long_auth = 'username:' + 'password'*10
>>> chr(10) in str(_encode_auth(long_auth))
False
"""
auth_s = urllib.parse.unquote(auth)
# convert to bytes
auth_bytes = auth_s.encode()
encoded_bytes = base64.b64encode(auth_bytes)
# convert back to a string
encoded = encoded_bytes.decode()
# strip the trailing carriage return
return encoded.replace('\n', '')
|
https://github.com/pypa/setuptools/blob/83c667e0b2a98193851c07115d1af65011ed0fb6/setuptools/package_index.py#L970-L989
|
encode url
|
python
|
def urlencode(resource):
"""
This implementation of urlencode supports all unicode characters
:param: resource: Resource value to be url encoded.
"""
if isinstance(resource, str):
return _urlencode(resource.encode('utf-8'))
return _urlencode(resource)
|
https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/compat.py#L96-L105
|
encode url
|
python
|
def url(self):
"Returns the URL that can be visited to obtain a verifier code"
# The authorize url is always api.xero.com
query_string = {'oauth_token': self.oauth_token}
if self.scope:
query_string['scope'] = self.scope
url = XERO_BASE_URL + AUTHORIZE_URL + '?' + \
urlencode(query_string)
return url
|
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L282-L292
|
encode url
|
python
|
def html_encode(path):
"""Return an HTML encoded Path.
:param path: ``str``
:return: ``str``
"""
if sys.version_info > (3, 2, 0):
return urllib.parse.quote(utils.ensure_string(path))
else:
return urllib.quote(utils.ensure_string(path))
|
https://github.com/cloudnull/cloudlib/blob/5038111ce02521caa2558117e3bae9e1e806d315/cloudlib/http.py#L58-L67
|
encode url
|
python
|
def get_code(self):
"""Opens the link and returns the response's content."""
if self.code is None:
self.code = urlopen(self.url).read()
return self.code
|
https://github.com/python-visualization/branca/blob/4e89e88a5a7ff3586f0852249c2c125f72316da8/branca/element.py#L177-L181
|
encode url
|
python
|
def _encode_auth(auth):
"""
A function compatible with Python 2.3-3.3 that will encode
auth from a URL suitable for an HTTP header.
>>> _encode_auth('username%3Apassword')
u'dXNlcm5hbWU6cGFzc3dvcmQ='
"""
auth_s = urllib2.unquote(auth)
# convert to bytes
auth_bytes = auth_s.encode()
# use the legacy interface for Python 2.3 support
encoded_bytes = base64.encodestring(auth_bytes)
# convert back to a string
encoded = encoded_bytes.decode()
# strip the trailing carriage return
return encoded.rstrip()
|
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/package_index.py#L813-L828
|
encode url
|
python
|
def uriencode(uristring, safe='', encoding='utf-8', errors='strict'):
"""Encode a URI string or string component."""
if not isinstance(uristring, bytes):
uristring = uristring.encode(encoding, errors)
if not isinstance(safe, bytes):
safe = safe.encode('ascii')
try:
encoded = _encoded[safe]
except KeyError:
encoded = _encoded[b''][:]
for i in _tointseq(safe):
encoded[i] = _fromint(i)
_encoded[safe] = encoded
return b''.join(map(encoded.__getitem__, _tointseq(uristring)))
|
https://github.com/tkem/uritools/blob/e77ba4acd937b68da9850138563debd4c925ef9f/uritools/encoding.py#L40-L53
|
encode url
|
python
|
def _encode_auth(auth):
"""
A function compatible with Python 2.3-3.3 that will encode
auth from a URL suitable for an HTTP header.
>>> str(_encode_auth('username%3Apassword'))
'dXNlcm5hbWU6cGFzc3dvcmQ='
Long auth strings should not cause a newline to be inserted.
>>> long_auth = 'username:' + 'password'*10
>>> chr(10) in str(_encode_auth(long_auth))
False
"""
auth_s = unquote(auth)
# convert to bytes
auth_bytes = auth_s.encode()
# use the legacy interface for Python 2.3 support
encoded_bytes = base64.encodestring(auth_bytes)
# convert back to a string
encoded = encoded_bytes.decode()
# strip the trailing carriage return
return encoded.replace('\n','')
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/package_index.py#L900-L920
|
encode url
|
python
|
def _url_base64_encode(msg):
"""
Base64 encodes a string using the URL-safe characters specified by
Amazon.
"""
msg_base64 = base64.b64encode(msg)
msg_base64 = msg_base64.replace('+', '-')
msg_base64 = msg_base64.replace('=', '_')
msg_base64 = msg_base64.replace('/', '~')
return msg_base64
|
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/cloudfront/distribution.py#L667-L676
|
encode url
|
python
|
def _encode_filename_header(self, filename):
"""
The filename, encoded to use in a ``Content-Disposition`` header.
"""
# Based on https://www.djangosnippets.org/snippets/1710/
user_agent = self.request.META.get('HTTP_USER_AGENT', None)
if 'WebKit' in user_agent:
# Support available for UTF-8 encoded strings.
# This also matches Edgee.
return u'filename={}'.format(filename).encode("utf-8")
elif 'MSIE' in user_agent:
# IE does not support RFC2231 for internationalized headers, but somehow
# percent-decodes it so this can be used instead. Note that using the word
# "attachment" anywhere in the filename overrides an inline content-disposition.
url_encoded = quote(filename.encode("utf-8")).replace('attachment', "a%74tachment")
return "filename={}".format(url_encoded).encode("utf-8")
else:
# For others like Firefox, we follow RFC2231 (encoding extension in HTTP headers).
rfc2231_filename = quote(filename.encode("utf-8"))
return "filename*=UTF-8''{}".format(rfc2231_filename).encode("utf-8")
|
https://github.com/edoburu/django-private-storage/blob/35b718024fee75b0ed3400f601976b20246c7d05/private_storage/views.py#L120-L139
|
encode url
|
python
|
def _foursquare_urlencode(query, doseq=0, safe_chars="&/,+"):
"""Gnarly hack because Foursquare doesn't properly handle standard url encoding"""
# Original doc: http://docs.python.org/2/library/urllib.html#urllib.urlencode
# Works the same way as urllib.urlencode except two differences -
# 1. it uses `quote()` instead of `quote_plus()`
# 2. it takes an extra parameter called `safe_chars` which is a string
# having the characters which should not be encoded.
#
# Courtesy of github.com/iambibhas
if hasattr(query,"items"):
# mapping objects
query = query.items()
else:
# it's a bother at times that strings and string-like objects are
# sequences...
try:
# non-sequence items should not work with len()
# non-empty strings will fail this
if len(query) and not isinstance(query[0], tuple):
raise TypeError
# zero-length sequences of all types will get here and succeed,
# but that's a minor nit - since the original implementation
# allowed empty dicts that type of behavior probably should be
# preserved for consistency
except TypeError:
ty,va,tb = sys.exc_info()
raise TypeError("not a valid non-string sequence or mapping object").with_traceback(tb)
l = []
if not doseq:
# preserve old behavior
for k, v in query:
k = parse.quote(_as_utf8(k), safe=safe_chars)
v = parse.quote(_as_utf8(v), safe=safe_chars)
l.append(k + '=' + v)
else:
for k, v in query:
k = parse.quote(_as_utf8(k), safe=safe_chars)
if isinstance(v, six.string_types):
v = parse.quote(_as_utf8(v), safe=safe_chars)
l.append(k + '=' + v)
else:
try:
# is this a sufficient test for sequence-ness?
len(v)
except TypeError:
# not a sequence
v = parse.quote(_as_utf8(v), safe=safe_chars)
l.append(k + '=' + v)
else:
# loop over the sequence
for elt in v:
l.append(k + '=' + parse.quote(_as_utf8(elt)))
return '&'.join(l)
|
https://github.com/mLewisLogic/foursquare/blob/420f3b588b9af154688ec82649f24a70f96c1665/foursquare/__init__.py#L811-L864
|
encode url
|
python
|
def from_url(cls, url, show_host=True):
'''Parse string and get URL instance'''
# url must be idna-encoded and url-quotted
if six.PY2:
if isinstance(url, six.text_type):
url = url.encode('utf-8')
parsed = urlparse(url)
netloc = parsed.netloc.decode('utf-8') # XXX HACK
else:# pragma: no cover
if isinstance(url, six.binary_type):
url = url.decode('utf-8', errors='replace') # XXX
parsed = urlparse(url)
netloc = parsed.netloc
query = _parse_qs(parsed.query)
host = netloc.split(':', 1)[0] if ':' in netloc else netloc
port = netloc.split(':')[1] if ':' in netloc else ''
path = unquote(parsed.path)
fragment = unquote(parsed.fragment)
if not fragment and not url.endswith('#'):
fragment = None
return cls(path,
query, host,
port, parsed.scheme, fragment, show_host)
|
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/web/url.py#L123-L148
|
encode url
|
python
|
def get_verify_code(self, file_path):
"""
获取登录验证码并存储
:param file_path: 将验证码图片保存的文件路径
"""
url = 'https://mp.weixin.qq.com/cgi-bin/verifycode'
payload = {
'username': self.__username,
'r': int(random.random() * 10000000000000),
}
headers = {
'referer': 'https://mp.weixin.qq.com/',
}
r = requests.get(url, data=payload, headers=headers, stream=True)
self.__cookies = ''
for cookie in r.cookies:
self.__cookies += cookie.name + '=' + cookie.value + ';'
with open(file_path, 'wb') as fd:
for chunk in r.iter_content(1024):
fd.write(chunk)
|
https://github.com/doraemonext/wechat-python-sdk/blob/bf6f6f3d4a5440feb73a51937059d7feddc335a0/wechat_sdk/ext.py#L104-L125
|
encode url
|
python
|
def unicode_urlencode(obj, charset='utf-8'):
"""URL escapes a single bytestring or unicode string with the
given charset if applicable to URL safe quoting under all rules
that need to be considered under all supported Python versions.
If non strings are provided they are converted to their unicode
representation first.
"""
if not isinstance(obj, string_types):
obj = text_type(obj)
if isinstance(obj, text_type):
obj = obj.encode(charset)
return text_type(url_quote(obj))
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/jinja2/utils.py#L279-L291
|
encode url
|
python
|
def encode(cls, d):
"""
Internal: encode a string for url representation
"""
warnings.warn(
'The `encode` class method of APIRequestor is deprecated and '
'will be removed in version 2.0.'
'If you need public access to this function, please email us '
'at support@stripe.com.',
DeprecationWarning)
return urllib.urlencode(list(_api_encode(d)))
|
https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/stripe/api_requestor.py#L115-L125
|
encode url
|
python
|
def authorization_code(self, client_id, client_secret, code,
redirect_uri, grant_type='authorization_code'):
"""Authorization code grant
This is the OAuth 2.0 grant that regular web apps utilize in order
to access an API. Use this endpoint to exchange an Authorization Code
for a Token.
Args:
grant_type (str): Denotes the flow you're using. For authorization code
use authorization_code
client_id (str): your application's client Id
client_secret (str): your application's client Secret
code (str): The Authorization Code received from the /authorize Calls
redirect_uri (str, optional): This is required only if it was set at
the GET /authorize endpoint. The values must match
Returns:
access_token, id_token
"""
return self.post(
'https://{}/oauth/token'.format(self.domain),
data={
'client_id': client_id,
'client_secret': client_secret,
'code': code,
'grant_type': grant_type,
'redirect_uri': redirect_uri,
},
headers={'Content-Type': 'application/json'}
)
|
https://github.com/auth0/auth0-python/blob/34adad3f342226aaaa6071387fa405ab840e5c02/auth0/v3/authentication/get_token.py#L12-L47
|
encode url
|
python
|
def encodeToURL(self, server_url):
"""Encode this request as a URL to GET.
@param server_url: The URL of the OpenID server to make this request of.
@type server_url: str
@returntype: str
@raises NoReturnError: when I do not have a return_to.
"""
if not self.return_to:
raise NoReturnToError
# Imported from the alternate reality where these classes are used
# in both the client and server code, so Requests are Encodable too.
# That's right, code imported from alternate realities all for the
# love of you, id_res/user_setup_url.
q = {'mode': self.mode,
'identity': self.identity,
'claimed_id': self.claimed_id,
'return_to': self.return_to}
if self.trust_root:
if self.message.isOpenID1():
q['trust_root'] = self.trust_root
else:
q['realm'] = self.trust_root
if self.assoc_handle:
q['assoc_handle'] = self.assoc_handle
response = Message(self.message.getOpenIDNamespace())
response.updateArgs(OPENID_NS, q)
return response.toURL(server_url)
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L883-L914
|
encode url
|
python
|
def url_quote(s, charset='utf-8', safe='/:'):
"""URL encode a single string with a given encoding.
:param s: the string to quote.
:param charset: the charset to be used.
:param safe: an optional sequence of safe characters.
"""
if isinstance(s, unicode):
s = s.encode(charset)
elif not isinstance(s, str):
s = str(s)
return _quote(s, safe=safe)
|
https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_urls.py#L383-L394
|
encode url
|
python
|
def urlencode_utf8(params):
"""
UTF-8 safe variant of urllib.urlencode.
http://stackoverflow.com/a/8152242
"""
if hasattr(params, 'items'):
params = params.items()
params = (
'='.join((
quote_plus(k.encode('utf8'), safe='/'),
quote_plus(v.encode('utf8'), safe='/')
)) for k, v in params
)
return '&'.join(params)
|
https://github.com/vilisov/gcm/blob/a2fb9f027c6c21b44e149c6ca32983a571c8a480/gcm/base.py#L83-L96
|
encode url
|
python
|
def percent_encode_non_ascii_headers(self, encoding='UTF-8'):
""" Encode any headers that are not plain ascii
as UTF-8 as per:
https://tools.ietf.org/html/rfc8187#section-3.2.3
https://tools.ietf.org/html/rfc5987#section-3.2.2
"""
def do_encode(m):
return "*={0}''".format(encoding) + quote(to_native_str(m.group(1)))
for index in range(len(self.headers) - 1, -1, -1):
curr_name, curr_value = self.headers[index]
try:
# test if header is ascii encodable, no action needed
curr_value.encode('ascii')
except:
new_value = self.ENCODE_HEADER_RX.sub(do_encode, curr_value)
if new_value == curr_value:
new_value = quote(curr_value)
self.headers[index] = (curr_name, new_value)
|
https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/statusandheaders.py#L176-L195
|
encode url
|
python
|
def get_response_code(url, timeout=10):
'''
Visit the URL and return the HTTP response code in 'int'
'''
try:
req = urllib2.urlopen(url, timeout=timeout)
except HTTPError, e:
return e.getcode()
except Exception, _:
fail("Couldn't reach the URL '%s'" % url)
else:
return req.getcode()
|
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/web.py#L35-L46
|
encode url
|
python
|
def unicode_urlencode(obj, charset='utf-8', for_qs=False):
"""URL escapes a single bytestring or unicode string with the
given charset if applicable to URL safe quoting under all rules
that need to be considered under all supported Python versions.
If non strings are provided they are converted to their unicode
representation first.
"""
if not isinstance(obj, string_types):
obj = text_type(obj)
if isinstance(obj, text_type):
obj = obj.encode(charset)
safe = not for_qs and b'/' or b''
rv = text_type(url_quote(obj, safe))
if for_qs:
rv = rv.replace('%20', '+')
return rv
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/utils.py#L287-L303
|
encode url
|
python
|
def _urlendecode(url, func):
"""Encode or decode ``url`` by applying ``func`` to all of its
URL-encodable parts.
"""
parsed = urlparse(url)
for attr in URL_ENCODABLE_PARTS:
parsed = parsed._replace(**{attr: func(getattr(parsed, attr))})
return urlunparse(parsed)
|
https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/utils.py#L45-L52
|
encode url
|
python
|
def urlencode_params(params):
"""URL encodes the parameters.
:param params: The parameters
:type params: list of key/value tuples.
:rtype: string
"""
# urlencode does not handle unicode strings in Python 2.
# Firstly, normalize the values so they get encoded correctly.
params = [(key, normalize_for_urlencode(val)) for key, val in params]
# Secondly, unquote unreserved chars which are incorrectly quoted
# by urllib.urlencode, causing invalid auth signatures. See GH #72
# for more info.
return requests.utils.unquote_unreserved(urlencode(params))
|
https://github.com/googlemaps/google-maps-services-python/blob/7ed40b4d8df63479794c46ce29d03ed6083071d7/googlemaps/client.py#L416-L430
|
encode url
|
python
|
def base64_encode(string):
"""base64 encodes a single bytestring (and is tolerant to getting
called with a unicode string).
The resulting bytestring is safe for putting into URLs.
"""
string = want_bytes(string)
return base64.urlsafe_b64encode(string).strip(b'=')
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L201-L207
|
encode url
|
python
|
def _encode_string(string):
"""Return a byte string, encoding Unicode with UTF-8."""
if not isinstance(string, bytes):
string = string.encode('utf8')
return ffi.new('char[]', string)
|
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/fonts.py#L16-L20
|
encode url
|
python
|
def encodePathElement(element):
"""Encode a URL path element according to RFC3986."""
return urllib.parse.quote(
(
element.encode('utf-8')
if isinstance(element, str)
else str(element)
if isinstance(element, int)
else element
),
safe=d1_common.const.URL_PATHELEMENT_SAFE_CHARS,
)
|
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/url.py#L59-L70
|
encode url
|
python
|
def authcode_get(self, path, **kwargs):
"""Perform an HTTP GET to okcupid.com using this profiles session
where the authcode is automatically added as a query parameter.
"""
kwargs.setdefault('params', {})['authcode'] = self.authcode
return self._session.okc_get(path, **kwargs)
|
https://github.com/IvanMalison/okcupyd/blob/46f4eaa9419098f6c299738ce148af55c64deb64/okcupyd/profile.py#L367-L372
|
encode url
|
python
|
def percent_encode_host(url):
""" Convert the host of uri formatted with to_uri()
to have a %-encoded host instead of punycode host
The rest of url should be unchanged
"""
# only continue if punycode encoded
if 'xn--' not in url:
return url
parts = urlsplit(url)
domain = parts.netloc.encode('utf-8')
try:
domain = domain.decode('idna')
if six.PY2:
domain = domain.encode('utf-8', 'ignore')
except:
# likely already encoded, so use as is
pass
domain = quote(domain)#, safe=r':\/')
return urlunsplit((parts[0], domain, parts[2], parts[3], parts[4]))
|
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/rewrite/wburl.py#L108-L130
|
encode url
|
python
|
def url(self, text, **kwargs):
"""Add URL Address data to Batch object.
Args:
text (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of URL.
"""
indicator_obj = URL(text, **kwargs)
return self._indicator(indicator_obj)
|
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L1606-L1621
|
encode url
|
python
|
def _encodeHeader(headerValue):
"""
Encodes a header value.
Returns ASCII if possible, else returns an UTF-8 encoded e-mail header.
"""
try:
return headerValue.encode('ascii', 'strict')
except UnicodeError:
encoded = headerValue.encode("utf-8")
return header.Header(encoded, "UTF-8").encode()
|
https://github.com/lvh/txeasymail/blob/7b845a5238b1371824854468646d54653a426f09/txeasymail/mime.py#L37-L47
|
encode url
|
python
|
def _qr_code(self, instance):
"""
return generate html code with "otpauth://..." link and QR-code
"""
request = self.request # FIXME
try:
user = instance.user
except ObjectDoesNotExist:
return _("Please save first!")
current_site = get_current_site(request)
username = user.username
secret = six.text_type(base64.b32encode(instance.bin_key), encoding="ASCII")
key_uri = (
"otpauth://totp/secure-login:%(site_name)s-%(username)s?secret=%(secret)s&issuer=%(issuer)s"
) % {
"site_name": urlquote(current_site.name),
"username": urlquote(username),
"secret": secret,
"issuer": urlquote(username),
}
context = {"key_uri": key_uri}
return render_to_string("secure_js_login/qr_info.html", context)
|
https://github.com/discontinue/django-secure-js-login/blob/4bfc592c48f381de115e592e721f31d2eb915968/secure_js_login/admin.py#L53-L76
|
encode url
|
python
|
def url_decode(url):
"""
URL Decode function using REGEX
**Parameters:**
- **url:** URLENCODED text string
**Returns:** Non URLENCODED string
"""
return re.compile('%([0-9a-fA-F]{2})', re.M).sub(lambda m: chr(int(m.group(1), 16)), url)
|
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/__init__.py#L1072-L1082
|
encode url
|
python
|
def url_fix(s, charset='utf-8'):
r"""Sometimes you get an URL by a user that just isn't a real URL because
it contains unsafe characters like ' ' and so on. This function can fix
some of the problems in a similar way browsers handle data entered by the
user:
>>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)')
'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29'
:param s: the string with the URL to fix.
:param charset: The target charset for the URL if the url was given as
unicode string.
"""
if isinstance(s, unicode):
s = s.encode(charset, 'replace')
scheme, netloc, path, qs, anchor = _safe_urlsplit(s)
path = _quote(path, '/%')
qs = _quote_plus(qs, ':&%=')
return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))
|
https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_urls.py#L445-L463
|
encode url
|
python
|
def b64encode(s, altchars=None):
"""Encode a string using Base64.
s is the string to encode. Optional altchars must be a string of at least
length 2 (additional characters are ignored) which specifies an
alternative alphabet for the '+' and '/' characters. This allows an
application to e.g. generate url or filesystem safe Base64 strings.
The encoded string is returned.
"""
# Strip off the trailing newline
encoded = binascii.b2a_base64(s)[:-1]
if altchars is not None:
return encoded.translate(string.maketrans(b'+/', altchars[:2]))
return encoded
|
https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/base64.py#L44-L58
|
encode url
|
python
|
def exchange_code(self, code, redirect_uri):
"""
Exchanges code for token/s
"""
token = requests.post(GOOGLE_OAUTH2_TOKEN_URL, data=dict(
code=code,
redirect_uri=redirect_uri,
grant_type='authorization_code',
client_id=self.client_id,
client_secret=self.client_secret,
)).json()
if not token or token.get('error'):
abort(400)
return token
|
https://github.com/insynchq/flask-googlelogin/blob/67346d232414fdba7283f516cb7540d41134d175/flask_googlelogin.py#L127-L141
|
encode url
|
python
|
def header_encode(header_bytes, charset='iso-8859-1'):
"""Encode a single header line with Base64 encoding in a given charset.
charset names the character set to use to encode the header. It defaults
to iso-8859-1. Base64 encoding is defined in RFC 2045.
"""
if not header_bytes:
return ""
if isinstance(header_bytes, str):
header_bytes = header_bytes.encode(charset)
encoded = b64encode(header_bytes).decode("ascii")
return '=?%s?b?%s?=' % (charset, encoded)
|
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/base64mime.py#L64-L75
|
encode url
|
python
|
def url_quote(string, charset='utf-8', errors='strict', safe='/:'):
"""URL encode a single string with a given encoding.
:param s: the string to quote.
:param charset: the charset to be used.
:param safe: an optional sequence of safe characters.
"""
if not isinstance(string, (text_type, bytes, bytearray)):
string = text_type(string)
if isinstance(string, text_type):
string = string.encode(charset, errors)
if isinstance(safe, text_type):
safe = safe.encode(charset, errors)
safe = frozenset(bytearray(safe) + _always_safe)
rv = bytearray()
for char in bytearray(string):
if char in safe:
rv.append(char)
else:
rv.extend(('%%%02X' % char).encode('ascii'))
return to_native(bytes(rv))
|
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/urls.py#L374-L394
|
encode url
|
python
|
def url(self):
"""
Return the URL of the server.
:returns: URL of the server
:rtype: string
"""
if len(self.drivers) > 0:
return self.drivers[0].url
else:
return self._url
|
https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/core.py#L86-L96
|
encode url
|
python
|
def parse_code(url):
"""
Parse the code parameter from the a URL
:param str url: URL to parse
:return: code query parameter
:rtype: str
"""
result = urlparse(url)
query = parse_qs(result.query)
return query['code']
|
https://github.com/jingming/spotify/blob/d92c71073b2515f3c850604114133a7d2022d1a4/spotify/auth/util.py#L6-L16
|
encode url
|
python
|
def get_authorization_code_uri(self, **params):
"""Construct a full URL that can be used to obtain an authorization
code from the provider authorization_uri. Use this URI in a client
frame to cause the provider to generate an authorization code.
:rtype: str
"""
if 'response_type' not in params:
params['response_type'] = self.default_response_type
params.update({'client_id': self.client_id,
'redirect_uri': self.redirect_uri})
return utils.build_url(self.authorization_uri, params)
|
https://github.com/NateFerrero/oauth2lib/blob/d161b010f8a596826050a09e5e94d59443cc12d9/oauth2lib/client.py#L49-L60
|
encode url
|
python
|
def url(self, endpoint):
"""
Returns full URL for specified API endpoint
>>> translate = YandexTranslate("trnsl.1.1.20130421T140201Z.323e508a33e9d84b.f1e0d9ca9bcd0a00b0ef71d82e6cf4158183d09e")
>>> translate.url("langs")
'https://translate.yandex.net/api/v1.5/tr.json/getLangs'
>>> translate.url("detect")
'https://translate.yandex.net/api/v1.5/tr.json/detect'
>>> translate.url("translate")
'https://translate.yandex.net/api/v1.5/tr.json/translate'
"""
return self.api_url.format(version=self.api_version,
endpoint=self.api_endpoints[endpoint])
|
https://github.com/dveselov/python-yandex-translate/blob/f26e624f683f10b4e7bf630b40d97241d82d5b01/yandex_translate/__init__.py#L47-L59
|
encode url
|
python
|
def header_encode(header_bytes, charset='iso-8859-1'):
"""Encode a single header line with quoted-printable (like) encoding.
Defined in RFC 2045, this `Q' encoding is similar to quoted-printable, but
used specifically for email header fields to allow charsets with mostly 7
bit characters (and some 8 bit) to remain more or less readable in non-RFC
2045 aware mail clients.
charset names the character set to use in the RFC 2046 header. It
defaults to iso-8859-1.
"""
# Return empty headers as an empty string.
if not header_bytes:
return ''
# Iterate over every byte, encoding if necessary.
encoded = []
for octet in header_bytes:
encoded.append(_QUOPRI_HEADER_MAP[octet])
# Now add the RFC chrome to each encoded chunk and glue the chunks
# together.
return '=?%s?q?%s?=' % (charset, EMPTYSTRING.join(encoded))
|
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/quoprimime.py#L132-L152
|
encode url
|
python
|
def url_fix(s, charset='utf-8'):
r"""Sometimes you get an URL by a user that just isn't a real URL because
it contains unsafe characters like ' ' and so on. This function can fix
some of the problems in a similar way browsers handle data entered by the
user:
>>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)')
'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)'
:param s: the string with the URL to fix.
:param charset: The target charset for the URL if the url was given as
unicode string.
"""
scheme, netloc, path, qs, anchor = url_parse(to_unicode(s, charset, 'replace'))
path = url_quote(path, charset, safe='/%+$!*\'(),')
qs = url_quote_plus(qs, charset, safe=':&%=+$!*\'(),')
return to_native(url_unparse((scheme, netloc, path, qs, anchor)))
|
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/urls.py#L475-L491
|
encode url
|
python
|
async def api_postcode(request):
"""
Gets data from a postcode.
:param request: The aiohttp request.
"""
postcode: Optional[str] = request.match_info.get('postcode', None)
try:
coroutine = get_postcode_random() if postcode == "random" else get_postcode(postcode)
postcode: Optional[Postcode] = await coroutine
except CachingError as e:
return web.HTTPInternalServerError(body=e.status)
except CircuitBreakerError as e:
pass
else:
if postcode is not None:
return str_json_response(postcode.serialize())
else:
return web.HTTPNotFound(body="Invalid Postcode")
|
https://github.com/arlyon/hyperion/blob/d8de0388ba98b85ce472e0f49ac18fecb14d3343/hyperion/api/geo.py#L13-L31
|
encode url
|
python
|
def authcode_post(self, path, **kwargs):
"""Perform an HTTP POST to okcupid.com using this profiles session
where the authcode is automatically added as a form item.
"""
kwargs.setdefault('data', {})['authcode'] = self.authcode
return self._session.okc_post(path, **kwargs)
|
https://github.com/IvanMalison/okcupyd/blob/46f4eaa9419098f6c299738ce148af55c64deb64/okcupyd/profile.py#L374-L379
|
encode url
|
python
|
def authorization_code(self, code, redirect_uri):
"""
Retrieve access token by `authorization_code` grant.
https://tools.ietf.org/html/rfc6749#section-4.1.3
:param str code: The authorization code received from the authorization
server.
:param str redirect_uri: the identical value of the "redirect_uri"
parameter in the authorization request.
:rtype: dict
:return: Access token response
"""
return self._token_request(grant_type='authorization_code', code=code,
redirect_uri=redirect_uri)
|
https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/openid_connect.py#L171-L185
|
encode url
|
python
|
def url_unquote(string, charset='utf-8', errors='replace', unsafe=''):
"""URL decode a single string with a given encoding. If the charset
is set to `None` no unicode decoding is performed and raw bytes
are returned.
:param s: the string to unquote.
:param charset: the charset of the query string. If set to `None`
no unicode decoding will take place.
:param errors: the error handling for the charset decoding.
"""
rv = _unquote_to_bytes(string, unsafe)
if charset is not None:
rv = rv.decode(charset, errors)
return rv
|
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/urls.py#L439-L452
|
encode url
|
python
|
def url(self):
"""return the full request url as an Url() instance"""
scheme = self.scheme
host = self.host
path = self.path
query = self.query
port = self.port
# normalize the port
host_domain, host_port = Url.split_hostname_from_port(host)
if host_port:
port = host_port
controller_path = ""
if self.controller_info:
controller_path = self.controller_info.get("path", "")
u = Url(
scheme=scheme,
hostname=host,
path=path,
query=query,
port=port,
controller_path=controller_path,
)
return u
|
https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/http.py#L943-L968
|
encode url
|
python
|
def exchange_code(self, code):
"""Exchange one-use code for an access_token and request_token."""
params = {'client_id': self.client_id,
'client_secret': self.client_secret,
'grant_type': 'authorization_code',
'code': code}
result = self._send_request(EXCHANGE_URL.format(self._base_url),
params=params, method='POST',
data_field=None)
self.access_token = result['access_token']
self.refresh_token = result['refresh_token']
return self.access_token, self.refresh_token
|
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L813-L824
|
encode url
|
python
|
def verifier(self, url):
""" Will ask user to click link to accept app and write code """
webbrowser.open(url)
print('A browser should have opened up with a link to allow us to access')
print('your account, follow the instructions on the link and paste the verifier')
print('Code into here to give us access, if the browser didn\'t open, the link is:')
print(url)
print()
return input('Verifier: ').lstrip(" ").rstrip(" ")
|
https://github.com/xray7224/PyPump/blob/f921f691c39fe021f4fd124b6bc91718c9e49b4a/docs/examples/pypump-post-note.py#L74-L82
|
encode url
|
python
|
def url_for(
endpoint: str,
*,
_anchor: Optional[str]=None,
_external: Optional[bool]=None,
_method: Optional[str]=None,
_scheme: Optional[str]=None,
**values: Any,
) -> str:
"""Return the url for a specific endpoint.
This is most useful in templates and redirects to create a URL
that can be used in the browser.
Arguments:
endpoint: The endpoint to build a url for, if prefixed with
``.`` it targets endpoint's in the current blueprint.
_anchor: Additional anchor text to append (i.e. #text).
_external: Return an absolute url for external (to app) usage.
_method: The method to consider alongside the endpoint.
_scheme: A specific scheme to use.
values: The values to build into the URL, as specified in
the endpoint rule.
"""
app_context = _app_ctx_stack.top
request_context = _request_ctx_stack.top
if request_context is not None:
url_adapter = request_context.url_adapter
if endpoint.startswith('.'):
if request.blueprint is not None:
endpoint = request.blueprint + endpoint
else:
endpoint = endpoint[1:]
if _external is None:
_external = False
elif app_context is not None:
url_adapter = app_context.url_adapter
if _external is None:
_external = True
else:
raise RuntimeError('Cannot create a url outside of an application context')
if url_adapter is None:
raise RuntimeError(
'Unable to create a url adapter, try setting the the SERVER_NAME config variable.'
)
if _scheme is not None and not _external:
raise ValueError('External must be True for scheme usage')
app_context.app.inject_url_defaults(endpoint, values)
try:
url = url_adapter.build(
endpoint, values, method=_method, scheme=_scheme, external=_external,
)
except BuildError as error:
return app_context.app.handle_url_build_error(error, endpoint, values)
if _anchor is not None:
quoted_anchor = quote(_anchor)
url = f"{url}#{quoted_anchor}"
return url
|
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/helpers.py#L137-L198
|
encode url
|
python
|
def toURLEncoded(self):
"""Generate an x-www-urlencoded string"""
args = sorted(self.toPostArgs().items())
return urllib.parse.urlencode(args)
|
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/message.py#L397-L400
|
encode url
|
python
|
def get_url_nofollow(url):
"""
function to get return code of a url
Credits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/
"""
try:
response = urlopen(url)
code = response.getcode()
return code
except HTTPError as e:
return e.code
except:
return 0
|
https://github.com/nikhilkumarsingh/content-downloader/blob/8b14af3a6eadcc43581e0425dc1d218208de12df/ctdl/ctdl.py#L81-L94
|
encode url
|
python
|
def url_fix(s, charset='utf-8'):
r"""Sometimes you get an URL by a user that just isn't a real URL because
it contains unsafe characters like ' ' and so on. This function can fix
some of the problems in a similar way browsers handle data entered by the
user:
>>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)')
'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)'
:param s: the string with the URL to fix.
:param charset: The target charset for the URL if the url was given as
unicode string.
"""
# First step is to switch to unicode processing and to convert
# backslashes (which are invalid in URLs anyways) to slashes. This is
# consistent with what Chrome does.
s = to_unicode(s, charset, 'replace').replace('\\', '/')
# For the specific case that we look like a malformed windows URL
# we want to fix this up manually:
if s.startswith('file://') and s[7:8].isalpha() and s[8:10] in (':/', '|/'):
s = 'file:///' + s[7:]
url = url_parse(s)
path = url_quote(url.path, charset, safe='/%+$!*\'(),')
qs = url_quote_plus(url.query, charset, safe=':&%=+$!*\'(),')
anchor = url_quote_plus(url.fragment, charset, safe=':&%=+$!*\'(),')
return to_native(url_unparse((url.scheme, url.encode_netloc(),
path, qs, anchor)))
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/werkzeug/urls.py#L548-L576
|
encode url
|
python
|
def safe_url(self, url, errors='strict'):
"""URL encode value for safe HTTP request.
Args:
url (string): The string to URL Encode.
Returns:
(string): The urlencoded string.
"""
if url is not None:
url = quote(self.s(url, errors=errors), safe='~')
return url
|
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L986-L997
|
encode url
|
python
|
def get_redirect_url(self, **kwargs):
"""
Return the authorization/authentication URL signed with the request
token.
"""
params = {
'oauth_token': self.get_request_token().key,
}
return '%s?%s' % (self.auth_url, urllib.urlencode(params))
|
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/clients/oauth.py#L154-L162
|
encode url
|
python
|
def authentication_url(self):
"""Redirect your users to here to authenticate them."""
params = {
'client_id': self.client_id,
'response_type': self.type,
'redirect_uri': self.callback_url
}
return AUTHENTICATION_URL + "?" + urlencode(params)
|
https://github.com/cenkalti/putio.py/blob/6ffe73002795f7362f54fab059e633c0c2620cfc/putiopy.py#L115-L122
|
encode url
|
python
|
def _encode_char(char, charmap, defaultchar):
""" Encode a single character with the given encoding map
:param char: char to encode
:param charmap: dictionary for mapping characters in this code page
"""
if ord(char) < 128:
return ord(char)
if char in charmap:
return charmap[char]
return ord(defaultchar)
|
https://github.com/python-escpos/python-escpos/blob/52719c0b7de8948fabdffd180a2d71c22cf4c02b/src/escpos/magicencode.py#L129-L139
|
encode url
|
python
|
def shortcode(self):
"""
This method returns the shortcode url of the listing.
:return:
"""
try:
div = self._ad_page_content.find(
'div', {'class': 'description_extras'})
index = [i for i, s in enumerate(
div.contents) if 'Shortcode' in str(s)][0] + 1
return div.contents[index]['href']
except Exception as e:
if self._debug:
logging.error(
"Error getting shortcode. Error message: " + e.args[0])
return 'N/A'
|
https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L383-L398
|
encode url
|
python
|
def get_code(self, id_code, access_token=None, user_id=None):
"""
Get a code, by its id
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsError('credentials invalid')
code = self.req.get('/Codes/' + id_code)
executions = self.req.get('/Codes/' + id_code + '/executions',
'&filter={"limit":3}')
if isinstance(executions, list):
code["executions"] = executions
return code
|
https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L553-L568
|
encode url
|
python
|
def url_to_string(url):
"""
Return the contents of a web site url as a string.
"""
try:
page = urllib2.urlopen(url)
except (urllib2.HTTPError, urllib2.URLError) as err:
ui.error(c.MESSAGES["url_unreachable"], err)
sys.exit(1)
return page
|
https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L92-L102
|
encode url
|
python
|
def construct_oauth_url(self):
""" Constructs verifier OAuth URL """
response = self._requester(requests.head,
"{0}://{1}/".format(self.protocol, self.client.server),
allow_redirects=False
)
if response.is_redirect:
server = response.headers['location']
else:
server = response.url
path = "oauth/authorize?oauth_token={token}".format(
token=self.store["oauth-request-token"]
)
return "{server}{path}".format(
server=server,
path=path
)
|
https://github.com/xray7224/PyPump/blob/f921f691c39fe021f4fd124b6bc91718c9e49b4a/pypump/pypump.py#L390-L407
|
encode url
|
python
|
def b64encode(s, altchars=None):
"""Encode bytes using the standard Base64 alphabet.
Argument ``s`` is a :term:`bytes-like object` to encode.
Optional ``altchars`` must be a byte string of length 2 which specifies
an alternative alphabet for the '+' and '/' characters. This allows an
application to e.g. generate url or filesystem safe Base64 strings.
The result is returned as a :class:`bytes` object.
"""
if altchars is not None:
altchars = _get_bytes(altchars)
assert len(altchars) == 2, repr(altchars)
if version_info < (3, 0):
if isinstance(s, text_type):
raise TypeError('a bytes-like object is required, not \''
+ type(s).__name__ + '\'')
return builtin_encode(s, altchars)
|
https://github.com/mayeut/pybase64/blob/861c48675fd6e37c129e1d7a1233074f8d54449e/pybase64/_fallback.py#L89-L107
|
encode url
|
python
|
def toURLEncoded(self):
"""Generate an x-www-urlencoded string"""
args = self.toPostArgs().items()
args.sort()
return urllib.urlencode(args)
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/message.py#L363-L367
|
encode url
|
python
|
def generate_code_challenge(verifier):
"""
source: https://github.com/openstack/deb-python-oauth2client
Creates a 'code_challenge' as described in section 4.2 of RFC 7636
by taking the sha256 hash of the verifier and then urlsafe
base64-encoding it.
Args:
verifier: bytestring, representing a code_verifier as generated by
generate_code_verifier().
Returns:
Bytestring, representing a urlsafe base64-encoded sha256 hash digest,
without '=' padding.
"""
digest = hashlib.sha256(verifier.encode('utf-8')).digest()
return base64.urlsafe_b64encode(digest).rstrip(b'=').decode('utf-8')
|
https://github.com/Kyria/EsiPy/blob/06407a0218a126678f80d8a7e8a67b9729327865/esipy/utils.py#L74-L88
|
encode url
|
python
|
def compare_response_code(url, code):
'''
Compare the response code of url param with code param and returns boolean
@param url -> string e.g. http://127.0.0.1/index
@param content_type -> int e.g. 404, 500, 400 ..etc
'''
try:
response = urllib2.urlopen(url)
except HTTPError as e:
return e.code == code
except:
return False
return response.code == code
|
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/web.py#L70-L85
|
encode url
|
python
|
def _encode_key(self, key):
"""Encode key using *hex_codec* for constructing a cache filename.
Keys are implicitly converted to :class:`bytes` if passed as
:class:`str`.
"""
if isinstance(key, str) or isinstance(key, unicode):
key = key.encode(self._keyencoding)
elif not isinstance(key, bytes):
raise TypeError("key must be bytes or str")
return codecs.encode(key, 'hex_codec').decode(self._keyencoding)
|
https://github.com/tsroten/fcache/blob/7ee3f385bc5f855e812f40d6af160ef7037a28e4/fcache/cache.py#L191-L202
|
encode url
|
python
|
def _http(method, url, headers=None, **kw):
'''
Send http request and return response text.
'''
params = None
boundary = None
if method == 'UPLOAD':
params, boundary = _encode_multipart(**kw)
else:
params = _encode_params(**kw)
http_url = '%s?%s' % (url, params) if method == _HTTP_GET else url
http_body = None if method == 'GET' else params
logging.error('%s: %s' % (method, http_url))
req = urllib2.Request(http_url, data=http_body)
req.add_header('Accept-Encoding', 'gzip')
if headers:
for k, v in headers.iteritems():
req.add_header(k, v)
if boundary:
req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
try:
resp = urllib2.urlopen(req, timeout=5)
return _read_http_body(resp)
finally:
pass
|
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L169-L193
|
encode url
|
python
|
def header_encode(self, string):
"""Header-encode a string by converting it first to bytes.
The type of encoding (base64 or quoted-printable) will be based on
this charset's `header_encoding`.
:param string: A unicode string for the header. It must be possible
to encode this string to bytes using the character set's
output codec.
:return: The encoded string, with RFC 2047 chrome.
"""
codec = self.output_codec or 'us-ascii'
header_bytes = _encode(string, codec)
# 7bit/8bit encodings return the string unchanged (modulo conversions)
encoder_module = self._get_encoder(header_bytes)
if encoder_module is None:
return string
return encoder_module.header_encode(header_bytes, codec)
|
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/charset.py#L284-L301
|
encode url
|
python
|
def gencode(self):
""" Run this to generate the code """
ledict = requests.get(self.api_url).json()
ledict = self.dotopdict(ledict)
out = self.dodict(ledict)
self._code = out
|
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/scigraph_codegen.py#L613-L618
|
encode url
|
python
|
def url_(client_id: str, redirect_uri: str, *, scope: str = None, state: str = None, secure: bool = True) -> str:
"""Construct a OAuth2 URL instead of an OAuth2 object."""
attrs = {
'client_id': client_id,
'redirect_uri': quote(redirect_uri)
}
if scope is not None:
attrs['scope'] = quote(scope)
if state is not None:
attrs['state'] = state
parameters = '&'.join('{0}={1}'.format(*item) for item in attrs.items())
return OAuth2._BASE.format(parameters=parameters)
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/utils.py#L111-L126
|
encode url
|
python
|
def _to_encoded_string(o):
"""
Build an encoded string suitable for use as a URL component. This includes double-escaping the string to
avoid issues with escaped backslash characters being automatically converted by WSGI or, in some cases
such as default Apache servers, blocked entirely.
:param o: an object of any kind, if it has an as_dict() method this will be used, otherwise uses __dict__
:return: an encoded string suitable for use as a URL component
:internal:
"""
_dict = o.__dict__
if o.as_dict:
_dict = o.as_dict()
return urllib.quote_plus(urllib.quote_plus(json.dumps(obj=_dict, separators=(',', ':'))))
|
https://github.com/camsci/meteor-pi/blob/7b01527650bd1b2b76d6f364e8122e25b8812c8d/src/pythonModules/meteorpi_client/meteorpi_client/__init__.py#L37-L50
|
encode url
|
python
|
def urlread(url, encoding='utf8'):
"""
Read the content of an URL.
Parameters
----------
url : str
Returns
-------
content : str
"""
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
response = urlopen(url)
content = response.read()
content = content.decode(encoding)
return content
|
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/io.py#L234-L253
|
encode url
|
python
|
def url(self, url, encoding="UTF-8"):
"""load and process the content behind a url
:return: the processed result of the :paramref:`url's <url>` content
:param str url: the url to retrieve the content from
:param str encoding: the encoding of the retrieved content.
The default encoding is UTF-8.
"""
import urllib.request
with urllib.request.urlopen(url) as file:
webpage_content = file.read()
webpage_content = webpage_content.decode(encoding)
return self.string(webpage_content)
|
https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Loader.py#L198-L211
|
encode url
|
python
|
def url_unquote(s, charset='utf-8', errors='replace'):
"""URL decode a single string with a given decoding.
Per default encoding errors are ignored. If you want a different behavior
you can set `errors` to ``'replace'`` or ``'strict'``. In strict mode a
`HTTPUnicodeError` is raised.
:param s: the string to unquote.
:param charset: the charset to be used.
:param errors: the error handling for the charset decoding.
"""
if isinstance(s, unicode):
s = s.encode(charset)
return _decode_unicode(_unquote(s), charset, errors)
|
https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_urls.py#L412-L425
|
encode url
|
python
|
def load_code(name, base_path=None, recurse=False):
"""Load executable code from a URL or a path"""
if '/' in name:
return load_location(name, base_path, module=False)
return importer.import_code(name, base_path, recurse=recurse)
|
https://github.com/timedata-org/loady/blob/94ffcdb92f15a28f3c85f77bd293a9cb59de4cad/loady/code.py#L64-L69
|
encode url
|
python
|
def fetch_by_code(self, code):
"""
Retrieves an auth code by its code.
:param code: The code of an auth code.
:return: An instance of :class:`oauth2.datatype.AuthorizationCode`.
:raises: :class:`oauth2.error.AuthCodeNotFound` if no auth code could
be retrieved.
"""
auth_code_data = self.fetchone(self.fetch_code_query, code)
if auth_code_data is None:
raise AuthCodeNotFound
data = dict()
data_result = self.fetchall(self.fetch_data_query, auth_code_data[0])
if data_result is not None:
for dataset in data_result:
data[dataset[0]] = dataset[1]
scopes = []
scope_result = self.fetchall(self.fetch_scopes_query,
auth_code_data[0])
if scope_result is not None:
for scope_set in scope_result:
scopes.append(scope_set[0])
return AuthorizationCode(client_id=auth_code_data[1],
code=auth_code_data[2],
expires_at=auth_code_data[3],
redirect_uri=auth_code_data[4],
scopes=scopes, data=data,
user_id=auth_code_data[5])
|
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/dbapi/__init__.py#L250-L284
|
encode url
|
python
|
def url(self):
"""
Get the ``xlink:href`` of this file.
"""
el_FLocat = self._el.find(TAG_METS_FLOCAT)
if el_FLocat is not None:
return el_FLocat.get("{%s}href" % NS["xlink"])
return ''
|
https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_file.py#L131-L138
|
encode url
|
python
|
def url_for(endpoint, default=DEFAULT_ENDPOINT, **values):
"""Looks up the API URL for the given endpoint
:param endpoint: The name of the registered route (aka endpoint)
:type endpoint: string
:returns: External URL for this endpoint
:rtype: string/None
"""
try:
return router.url_for(endpoint, force_external=True, values=values)
except Exception:
logger.warn("Could not build API URL for endpoint '%s'. "
"No route provider registered?" % endpoint)
# build generic API URL
return router.url_for(default, force_external=True, values=values)
|
https://github.com/senaite/senaite.jsonapi/blob/871959f4b1c9edbb477e9456325527ca78e13ec6/src/senaite/jsonapi/api.py#L1072-L1087
|
encode url
|
python
|
def authorization_code(self, request, data, client):
"""
Handle ``grant_type=authorization_code`` requests as defined in
:rfc:`4.1.3`.
"""
grant = self.get_authorization_code_grant(request, request.POST,
client)
if constants.SINGLE_ACCESS_TOKEN:
at = self.get_access_token(request, grant.user, grant.scope, client)
else:
at = self.create_access_token(request, grant.user, grant.scope, client)
rt = self.create_refresh_token(request, grant.user, grant.scope, at,
client)
self.invalidate_grant(grant)
return self.access_token_response(at)
|
https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/views.py#L494-L510
|
encode url
|
python
|
def isurl(self, string, *args):
"""Is url
args:
string (str): match
returns:
bool
"""
arg = utility.destring(string)
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+'
r'(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
# localhost...
r'localhost|'
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
# optional port
r'(?::\d+)?'
r'(?:/?|[/?]\S+)$',
re.IGNORECASE)
return regex.match(arg)
|
https://github.com/lesscpy/lesscpy/blob/51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126/lesscpy/plib/call.py#L124-L143
|
encode url
|
python
|
def get_authentication_tokens(self):
"""
get_auth_url(self)
Returns an authorization URL for a user to hit.
"""
callback_url = self.callback_url or 'oob'
request_args = {}
if OAUTH_LIB_SUPPORTS_CALLBACK:
request_args['callback_url'] = callback_url
resp, content = self.client.request(self.request_token_url,
"GET", **request_args)
if resp['status'] != '200':
raise AuthError("Seems something couldn't be verified "\
"withyour OAuth junk. Error: %s, Message: %s" \
% (resp['status'], content))
request_tokens = dict(urlparse.parse_qsl(content))
oauth_callback_confirmed = request_tokens\
.get('oauth_callback_confirmed') == 'true'
if not OAUTH_LIB_SUPPORTS_CALLBACK and callback_url != 'oob'\
and oauth_callback_confirmed:
import warnings
warnings.warn("oauth2 library doesn't support OAuth 1.0a"\
" type callback, but remote requires it")
oauth_callback_confirmed = False
auth_url_params = {'oauth_token': request_tokens['oauth_token']}
# Use old-style callback argument
if callback_url != 'oob' and not oauth_callback_confirmed:
auth_url_params['oauth_callback'] = callback_url
request_tokens['auth_url'] = self.authenticate_url + '?'\
+ urllib.urlencode(auth_url_params)
return request_tokens
|
https://github.com/ahmontero/django-twitter/blob/3da06115bb88a3409f0bb00dba6a618f7cd4d817/twitter/toauth.py#L73-L112
|
encode url
|
python
|
def url(self, request=""):
"""Build the url with the appended request if provided."""
if request.startswith("/"):
request = request[1:]
return "{}://{}/{}".format(self.scheme, self.host, request)
|
https://github.com/browniebroke/deezer-python/blob/fb869c3617045b22e7124e4b783ec1a68d283ac3/deezer/client.py#L95-L99
|
encode url
|
python
|
def url_for(endpoint, default="senaite.jsonapi.get", **values):
"""Looks up the API URL for the given endpoint
:param endpoint: The name of the registered route (aka endpoint)
:type endpoint: string
:returns: External URL for this endpoint
:rtype: string/None
"""
try:
return router.url_for(endpoint, force_external=True, values=values)
except Exception:
# XXX plone.jsonapi.core should catch the BuildError of Werkzeug and
# throw another error which can be handled here.
logger.debug("Could not build API URL for endpoint '%s'. "
"No route provider registered?" % endpoint)
# build generic API URL
return router.url_for(default, force_external=True, values=values)
|
https://github.com/senaite/senaite.jsonapi/blob/871959f4b1c9edbb477e9456325527ca78e13ec6/src/senaite/jsonapi/__init__.py#L25-L43
|
encode url
|
python
|
def urlopen_without_redirect(url, headers={}, data=None, retries=RETRIES):
'''请求一个URL, 并返回一个Response对象. 不处理重定向.
使用这个函数可以返回URL重定向(Error 301/302)后的地址, 也可以重到URL中请
求的文件的大小, 或者Header中的其它认证信息.
'''
headers_merged = default_headers.copy()
for key in headers.keys():
headers_merged[key] = headers[key]
parse_result = urllib.parse.urlparse(url)
for i in range(retries):
try:
conn = http.client.HTTPConnection(parse_result.netloc)
if data:
conn.request('POST', url, body=data, headers=headers_merged)
else:
conn.request('GET', url, body=data, headers=headers_merged)
return conn.getresponse()
except OSError:
logger.error(traceback.format_exc())
except:
logger.error(traceback.format_exc())
#return None
return None
|
https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/net.py#L110-L134
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.