本文整理汇总了Python中urllib.parse.unquote_plus函数的典型用法代码示例。如果您正苦于以下问题:Python unquote_plus函数的具体用法?Python unquote_plus怎么用?Python unquote_plus使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了unquote_plus函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:BluscreamFanBoy,项目名称:SteamSignInpy,代码行数:7,代码来源:SteamSignIn.py
示例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
开发者ID:BlazeMediaGroup,项目名称:mongo-python-driver,代码行数:25,代码来源:uri_parser.py
示例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=(',', ': ')))
开发者ID:rohe,项目名称:oidctest,代码行数:7,代码来源:asis.py
示例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
开发者ID:atareao,项目名称:imagedownloader,代码行数:7,代码来源:imagedownloader.py
示例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'
开发者ID:nbeguier,项目名称:cassh,代码行数:34,代码来源:server.py
示例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)
开发者ID:ZJDong,项目名称:Wayfindr-Py,代码行数:26,代码来源:uri_parser.py
示例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 {}
开发者ID:deluge-torrent,项目名称:deluge,代码行数:60,代码来源:common.py
示例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)
开发者ID:markschaver,项目名称:anonymous,代码行数:8,代码来源:anonymous.py
示例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
开发者ID:showermat,项目名称:zsr-utils,代码行数:8,代码来源:wikidump.py
示例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
开发者ID:saml,项目名称:x,代码行数:10,代码来源:waywire.py
示例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!")
开发者ID:django-searchstack,项目名称:skisolr,代码行数:10,代码来源:client.py
示例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})
开发者ID:canademar,项目名称:me_extractors,代码行数:11,代码来源:topic_service.py
示例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)
开发者ID:1stvamp,项目名称:tornado,代码行数:12,代码来源:escape.py
示例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
开发者ID:bernii,项目名称:querystring-parser,代码行数:52,代码来源:parser.py
示例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
开发者ID:rohe,项目名称:oidctest,代码行数:13,代码来源:action.py
示例16: 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!",
)
开发者ID:janurag,项目名称:pysolr,代码行数:13,代码来源:client.py
示例17: _parseBody
def _parseBody(self):
"""Parses the body of the request into a dictionary. At the moment only
application/x-www-form-urlencoded is supported!
"""
# If the content_type is defined and the content has a length try to parse the body
if self.content_type and self.content_length:
if self.content_type.startswith('application/x-www-form-urlencoded'):
self.body = MultiDict()
# Read the body from the virtual file
body = self.environment["wsgi.input"].read(self.content_length)
# Decode the body from its latin-1 decoding to a python string
body = body.decode('latin-1')
# Split the body into strings containing one key and one value
pairs = body.split('&')
# For each key value pair split it and decode it from urlencoded strings to a string
for pair in pairs:
(key, _, value) = pair.partition('=');
# Add key/value to MultiDict
self.body.append(unquote_plus(key), unquote_plus(value))
elif self.content_type.startswith("multipart/form-data"):
self.body = cgi.FieldStorage(fp=self.environment["wsgi.input"], environ=self.environment)
elif self.content_type.startswith("application/json"):
if "charset" in self.content_type:
try:
charset = self.content_type[self.content_type.find("charset"):].rpartition("=")[2]
except:
charset = "UTF8"
else:
charset = "UTF8"
# Read the body from the virtual file
body = self.environment["wsgi.input"].read(self.content_length)
# Decode the body
body = body.decode(charset)
self.body = json.loads(body)
elif self.content_length:
self.body = self.environment["wsgi.input"].read(self.content_length)
ß
else:
self.body = None
开发者ID:Simplendi,项目名称:SimpleFramework,代码行数:51,代码来源:request.py
示例18: _url_decode_impl
def _url_decode_impl(pair_iter, charset, keep_blank_values, errors):
for pair in pair_iter:
if not pair:
continue
equal = b'='
if equal in pair:
key, value = pair.split(equal, 1)
else:
if not keep_blank_values:
continue
key = pair
value = b''
yield unquote_plus(safe_str(key)), unquote_plus(safe_str(value),
charset, errors)
开发者ID:cymoo,项目名称:minim,代码行数:14,代码来源:formpaser.py
示例19: task_break_view
def task_break_view(task_id, task_date):
form = TaskBreakForm(request.form)
try:
task = Task.query.filter(
Task.id == task_id,
Task.owner_id == current_user.id,
).one()
except NoResultFound:
# This is not an existing task this user owns
flash(
'Could not find task {id}.'.format(id=task_id),
'danger',
)
return redirect(url_for('home'))
date = parse.unquote_plus(task_date)
if request.method == 'POST' and form.validate():
return try_to_take_task_break(
task_id=task_id,
form=form,
date=date,
)
else:
return render_turkey(
"task_break.html",
form=form,
task=task,
task_date=date,
)
开发者ID:geokala,项目名称:quizify,代码行数:30,代码来源:task_break.py
示例20: split_text
def split_text(text):
start = 0
text = quote_plus(text)
length = len(text)
while (length - start) > self._MAX_LENGTH_PER_QUERY:
for seperator in self._SEPERATORS:
index = text.rfind(seperator, start, start+self._MAX_LENGTH_PER_QUERY)
if index != -1:
break
else:
raise Error('input too large')
end = index + len(seperator)
yield unquote_plus(text[start:end])
start = end
yield unquote_plus(text[start:])
开发者ID:gzliuyun,项目名称:Translate,代码行数:16,代码来源:goslate.py
注:本文中的urllib.parse.unquote_plus函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论