本文整理汇总了Python中urllib.parse.unquote_plus函数的典型用法代码示例。如果您正苦于以下问题:Python unquote_plus函数的具体用法?Python unquote_plus怎么用?Python unquote_plus使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了unquote_plus函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: urlparamtodic
def urlparamtodic(self,data):
dic = {}
args = data.split('&')
for arg in args:
keyval = arg.split('=')
dic[parse.unquote_plus(keyval[0])] = parse.unquote_plus(keyval[1])
return dic
示例2: parse_userinfo
def parse_userinfo(userinfo):
"""Validates the format of user information in a MongoDB URI.
Reserved characters like ':', '/', '+' and '@' must be escaped
following RFC 2396.
Returns a 2-tuple containing the unescaped username followed
by the unescaped password.
:Paramaters:
- `userinfo`: A string of the form <username>:<password>
.. versionchanged:: 2.2
Now uses `urllib.unquote_plus` so `+` characters must be escaped.
"""
if '@' in userinfo or userinfo.count(':') > 1:
raise InvalidURI("':' or '@' characters in a username or password "
"must be escaped according to RFC 2396.")
user, _, passwd = _partition(userinfo, ":")
# No password is expected with GSSAPI authentication.
if not user:
raise InvalidURI("The empty string is not valid username.")
user = unquote_plus(user)
passwd = unquote_plus(passwd)
return user, passwd
示例3: print_conf
def print_conf(c):
iss, tag = c.split('][', 2)
fname= os.path.join('entities', quote_plus(unquote_plus(iss)), quote_plus(unquote_plus(tag)))
cnf = json.loads(open(fname,'r').read())
print(">>>", fname)
print(json.dumps(cnf, sort_keys=True, indent=2,
separators=(',', ': ')))
示例4: name_file
def name_file(imgUrl):
fileName = unquote_plus(unquote_plus(unquote_plus(basename(imgUrl))))
if os.path.exists(fileName):
base, ext = os.path.splitext(fileName)
nfiles = len(glob.glob(base+'*'+ext))
fileName = base+'_'+str(nfiles)+ext
return fileName
示例5: ldap_authentification
def ldap_authentification(admin=False):
"""
Return True if user is well authentified
[email protected]
password=xxxxx
"""
if SERVER_OPTS['ldap']:
credentials = data2map()
if 'realname' in credentials:
realname = unquote_plus(credentials['realname'])
else:
return False, 'Error: No realname option given.'
if 'password' in credentials:
password = unquote_plus(credentials['password'])
else:
return False, 'Error: No password option given.'
if password == '':
return False, 'Error: password is empty.'
ldap_conn = initialize("ldap://"+SERVER_OPTS['ldap_host'])
try:
ldap_conn.bind_s(realname, password)
except Exception as e:
return False, 'Error: %s' % e
if admin:
memberof_admin_list = ldap_conn.search_s(
SERVER_OPTS['ldap_bind_dn'],
SCOPE_SUBTREE,
filterstr='(&(%s=%s)(memberOf=%s))' % (
SERVER_OPTS['filterstr'],
realname,
SERVER_OPTS['ldap_admin_cn']))
if not memberof_admin_list:
return False, 'Error: user %s is not an admin.' % realname
return True, 'OK'
示例6: parse_userinfo
def parse_userinfo(userinfo):
"""Validates the format of user information in a MongoDB URI.
Reserved characters like ':', '/', '+' and '@' must be escaped
following RFC 3986.
Returns a 2-tuple containing the unescaped username followed
by the unescaped password.
:Paramaters:
- `userinfo`: A string of the form <username>:<password>
.. versionchanged:: 2.2
Now uses `urllib.unquote_plus` so `+` characters must be escaped.
"""
if '@' in userinfo or userinfo.count(':') > 1:
if PY3:
quote_fn = "urllib.parse.quote_plus"
else:
quote_fn = "urllib.quote_plus"
raise InvalidURI("Username and password must be escaped according to "
"RFC 3986, use %s()." % quote_fn)
user, _, passwd = _partition(userinfo, ":")
# No password is expected with GSSAPI authentication.
if not user:
raise InvalidURI("The empty string is not valid username.")
return unquote_plus(user), unquote_plus(passwd)
示例7: get_magnet_info
def get_magnet_info(uri):
"""Parse torrent information from magnet link.
Args:
uri (str): The magnet link.
Returns:
dict: Information about the magnet link.
Format of the magnet dict::
{
"name": the torrent name,
"info_hash": the torrents info_hash,
"files_tree": empty value for magnet links
}
"""
tr0_param = 'tr.'
tr0_param_regex = re.compile('^tr.(\d+)=(\S+)')
if not uri.startswith(MAGNET_SCHEME):
return {}
name = None
info_hash = None
trackers = {}
tier = 0
for param in uri[len(MAGNET_SCHEME):].split('&'):
if param.startswith(XT_BTIH_PARAM):
xt_hash = param[len(XT_BTIH_PARAM):]
if len(xt_hash) == 32:
try:
info_hash = base64.b32decode(xt_hash.upper()).encode('hex')
except TypeError as ex:
log.debug('Invalid base32 magnet hash: %s, %s', xt_hash, ex)
break
elif is_infohash(xt_hash):
info_hash = xt_hash.lower()
else:
break
elif param.startswith(DN_PARAM):
name = unquote_plus(param[len(DN_PARAM):])
elif param.startswith(TR_PARAM):
tracker = unquote_plus(param[len(TR_PARAM):])
trackers[tracker] = tier
tier += 1
elif param.startswith(tr0_param):
try:
tier, tracker = re.match(tr0_param_regex, param).groups()
trackers[tracker] = tier
except AttributeError:
pass
if info_hash:
if not name:
name = info_hash
return {'name': name, 'info_hash': info_hash, 'files_tree': '', 'trackers': trackers}
else:
return {}
示例8: article
def article(outlet, pub_date, title):
outlet_url = get_outlet_url(outlet)
title = parse.unquote_plus(title)
results = get_page_info(outlet_url, pub_date, title)
masthead = parse.unquote_plus(outlet)
return render_template('article.html',
masthead=masthead,
results=results)
示例9: queryparse
def queryparse(query):
ret = dict()
for kvpair in query.split("&"):
try:
(key, val) = kvpair.split("=")
ret[unquote_plus(key)] = unquote_plus(val)
except Exception: continue
return ret
示例10: fetch_embed_player
def fetch_embed_player(url):
resp = fetch(url)
html = unquote_plus(resp.text)
cid = find_cid(html)
if cid:
# url was a redirect page, not actual video player.
embed_url = '{}/embed/player/container/1920/922/?content={}&widget_type_cid=cvp'.format(base_url(url), cid)
resp = fetch(embed_url)
return unquote_plus(resp.text)
return html
示例11: test_safe_urlencode
def test_safe_urlencode(self):
self.assertEqual(
force_unicode(unquote_plus(safe_urlencode({'test': 'Hello ☃! Helllo world!'}))),
'test=Hello ☃! Helllo world!')
self.assertEqual(
force_unicode(unquote_plus(safe_urlencode({'test': ['Hello ☃!', 'Helllo world!']}, True))),
"test=Hello \u2603!&test=Helllo world!")
self.assertEqual(
force_unicode(unquote_plus(safe_urlencode({'test': ('Hello ☃!', 'Helllo world!')}, True))),
"test=Hello \u2603!&test=Helllo world!")
示例12: post
def post(self):
results = list()
logging.debug("Received POST request")
for line in str(self.request.body, 'utf8').split('\n'):
fields = line.split('\t')
text = unquote_plus(unquote_plus(fields[0]))
logging.debug("Classificating %s" % text)
classification = self.default_classificator.classify(text)
result = {"text":text, "topics":self.__get_concepts_from_classification(classification)}
results.append(result)
self.write({"response":results})
示例13: url_unescape
def url_unescape(value, encoding='utf-8'):
"""Decodes the given value from a URL.
The argument may be either a byte or unicode string.
If encoding is None, the result will be a byte string. Otherwise,
the result is a unicode string in the specified encoding.
"""
if encoding is None:
return urllib_parse.unquote_plus(utf8(value))
else:
return unicode_type(urllib_parse.unquote_plus(utf8(value)), encoding)
示例14: parse
def parse(query_string, unquote=True, normalized=False, encoding=DEFAULT_ENCODING):
"""
Main parse function
@param query_string:
@param unquote: unquote html query string ?
@param encoding: An optional encoding used to decode the keys and values. Defaults to utf-8, which the W3C declares as a defaul in the W3C algorithm for encoding.
@see http://www.w3.org/TR/html5/forms.html#application/x-www-form-urlencoded-encoding-algorithm
@param normalized: parse number key in dict to proper list ?
"""
mydict = {}
plist = []
if query_string == "":
return mydict
if type(query_string) == bytes:
query_string = query_string.decode()
for element in query_string.split("&"):
try:
if unquote:
(var, val) = element.split("=")
if sys.version_info[0] == 2:
var = var.encode("ascii")
val = val.encode("ascii")
var = urllib.unquote_plus(var)
val = urllib.unquote_plus(val)
else:
(var, val) = element.split("=")
except ValueError:
raise MalformedQueryStringError
if encoding:
var = var.decode(encoding)
val = val.decode(encoding)
plist.append(parser_helper(var, val))
for di in plist:
(k, v) = di.popitem()
tempdict = mydict
while k in tempdict and type(v) is dict:
tempdict = tempdict[k]
(k, v) = v.popitem()
if k in tempdict and type(tempdict[k]).__name__ == "list":
tempdict[k].append(v)
elif k in tempdict:
tempdict[k] = [tempdict[k], v]
else:
tempdict[k] = v
if normalized == True:
return _normalize(mydict)
return mydict
示例15: _cp_dispatch
def _cp_dispatch(self, vpath):
# Only get here if vpath != None
ent = cherrypy.request.remote.ip
logger.info('ent:{}, vpath: {}'.format(ent, vpath))
if len(vpath):
if len(vpath) == 2:
cherrypy.request.params['iss'] = unquote_plus(vpath.pop(0))
cherrypy.request.params['tag'] = unquote_plus(vpath.pop(0))
cherrypy.request.params['ev'] = init_events(
cherrypy.request.path_info)
return self