本文整理汇总了Python中urllib.parse.unquote方法的典型用法代码示例。如果您正苦于以下问题:Python parse.unquote方法的具体用法?Python parse.unquote怎么用?Python parse.unquote使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类urllib.parse
的用法示例。
在下文中一共展示了parse.unquote方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: handle_starttag
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def handle_starttag(self, tag, attrs):
if re.match("h[1-6]", tag) is not None:
self.ishead = True
elif tag in self.inde:
self.isinde = True
elif tag in self.pref:
self.ispref = True
elif tag in self.bull:
self.isbull = True
elif tag in self.hide:
self.ishidden = True
elif tag == "sup":
self.text[-1] += "^{"
elif tag == "sub":
self.text[-1] += "_{"
elif tag == "image":
for i in attrs:
if i[0] == "xlink:href":
self.text.append("[IMG:{}]".format(len(self.imgs)))
self.imgs.append(unquote(i[1]))
示例2: test_file_response_custom_filename
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def test_file_response_custom_filename(
app, source, dest, static_file_directory
):
@app.route("/files/<filename>", methods=["GET"])
def file_route(request, filename):
file_path = os.path.join(static_file_directory, filename)
file_path = os.path.abspath(unquote(file_path))
return file(file_path, filename=dest)
request, response = app.test_client.get(f"/files/{source}")
assert response.status == 200
assert response.body == get_file_content(static_file_directory, source)
assert (
response.headers["Content-Disposition"]
== f'attachment; filename="{dest}"'
)
示例3: test_file_stream_response_custom_filename
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def test_file_stream_response_custom_filename(
app, source, dest, static_file_directory
):
@app.route("/files/<filename>", methods=["GET"])
def file_route(request, filename):
file_path = os.path.join(static_file_directory, filename)
file_path = os.path.abspath(unquote(file_path))
return file_stream(file_path, chunk_size=32, filename=dest)
request, response = app.test_client.get(f"/files/{source}")
assert response.status == 200
assert response.body == get_file_content(static_file_directory, source)
assert (
response.headers["Content-Disposition"]
== f'attachment; filename="{dest}"'
)
示例4: fwd_normalize
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def fwd_normalize(fwd: OptionsIterable) -> Options:
"""Normalize and convert values extracted from forwarded headers."""
ret: Dict[str, Union[int, str]] = {}
for key, val in fwd:
if val is not None:
try:
if key in ("by", "for"):
ret[key] = fwd_normalize_address(val)
elif key in ("host", "proto"):
ret[key] = val.lower()
elif key == "port":
ret[key] = int(val)
elif key == "path":
ret[key] = unquote(val)
else:
ret[key] = val
except ValueError:
pass
return ret
示例5: put
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def put(url, data):
url = unquote(url)
match, project = Cache.match(url)
if match:
path = Cache.path(url, project, include_file=True, makedirs=True)
ttl = Cache.PATTERNS[match]
if ttl == 0:
return data
# Since urlopen does not return a seekable stream it cannot be reset
# after writing to cache. As such a wrapper must be used. This could
# be replaced with urlopen('file://...') to be consistent, but until
# the need arrises BytesIO has less overhead.
text = data.read()
data = BytesIO(text)
if conf.config['debug']: print('CACHE_PUT', url, project, file=sys.stderr)
f = open(path, 'wb')
f.write(text)
f.close()
return data
示例6: delete
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def delete(url):
url = unquote(url)
match, project = Cache.match(url)
if match:
path = Cache.path(url, project, include_file=True)
# Rather then wait for last updated statistics to expire, remove the
# project cache if applicable.
if project:
apiurl, _ = Cache.spliturl(url)
if project.isdigit():
# Clear target project cache upon request acceptance.
project = osc.core.get_request(apiurl, project).actions[0].tgt_project
Cache.delete_project(apiurl, project)
if os.path.exists(path):
if conf.config['debug']: print('CACHE_DELETE', url, file=sys.stderr)
os.remove(path)
# Also delete version without query. This does not handle other
# variations using different query strings. Handy for PUT with ?force=1.
o = urlsplit(url)
if o.query != '':
url_plain = SplitResult(o.scheme, o.netloc, o.path, '', o.fragment).geturl()
Cache.delete(url_plain)
示例7: find_file
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def find_file(self, filename):
# Get rid of special characters
filename = unquote(filename)
# First, look for the file in the root of the book
if filename in self.file_list:
return filename
# Then search for it elsewhere
else:
file_basename = os.path.basename(filename)
for i in self.file_list:
if os.path.basename(i) == file_basename:
return i
# If the file isn't found
logger.warning(filename + ' not found in ' + self.book_filename)
return False
示例8: test_form_link
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def test_form_link(self):
data = {
'pid': 99,
'account': 79000000000,
'amount': 123,
'comment': 'Hey, it works!'
}
paylink = pyqiwi.generate_form_link(**data)
result = url_params(unquote(paylink))
data.pop('pid') # It is not on params, it's in URL
# Qiwi requires for amount to be split into integer and fraction
data = merge_dicts(data, split_float(data.get('amount')))
data.pop('amount')
# unquote won't process + to <Space>, but Qiwi should
if result.get("extra['comment']"):
result["extra['comment']"] = result["extra['comment']"].replace('+', ' ')
for key in data:
if key == 'account':
assert result["extra['account']"] == str(data[key])
elif key == 'comment':
assert result["extra['comment']"] == str(data[key])
示例9: getguild
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def getguild(self, request: web.Request):
guild = int(request.match_info['guild'])
req = f"""SELECT info FROM guilddata WHERE UUID = $1"""
async with self.bot.db._conn.acquire() as connection:
response = await connection.fetchval(req, guild)
if response:
data = json.loads(response)
fdata = data
if request.match_info['tail']:
for item in request.match_info['tail'].split("/"):
if not item:
continue
try:
key = unquote(item)
if isinstance(fdata, list):
key = int(key)
fdata = fdata[key]
except:
raise web.HTTPNotFound()
return web.json_response(fdata)
raise web.HTTPForbidden()
# @server.route("/", methods=["GET"])
示例10: __init__
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def __init__(self, url):
super(ElasticDB, self).__init__()
self.username = ''
self.password = ''
self.hosts = None
if '@' in url.netloc:
username, hostname = url.netloc.split('@', 1)
if ':' in username:
self.username, self.password = (unquote(val) for val in
username.split(':', 1))
else:
self.username = unquote(username)
if hostname:
self.hosts = [hostname]
elif url.netloc:
self.hosts = [url.netloc]
index_prefix = url.path.lstrip('/')
if index_prefix:
self.index_prefix = index_prefix + '-'
else:
self.index_prefix = 'ivre-'
self.params = dict(x.split('=', 1) if '=' in x else (x, None)
for x in url.query.split('&') if x)
示例11: article
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def article(
self,
title: str,
ns: WikiNamespace = Namespace.MAIN,
unquote: bool = False
) -> 'WikipediaPage':
"""
Constructs Wikipedia page with title `title`.
This function is an alias for :func:`page`
:param title: page title as used in Wikipedia URL
:param ns: :class:`WikiNamespace`
:param unquote: if true it will unquote title
:return: object representing :class:`WikipediaPage`
"""
return self.page(
title=title,
ns=ns,
unquote=unquote,
)
示例12: translate_path
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def translate_path(self, path):
"""
Translate a /-separated PATH to the local filename syntax.
Components that mean special things to the local file system
(e.g. drive or directory names) are ignored. (XXX They should
probably be diagnosed.)
"""
# abandon query parameters
path = urlparse(to_text(path))[2]
path = posixpath.normpath(unquote(path))
words = path.split('/')
words = list(filter(None, words))
path = self.server.cwd
for word in words:
_, word = os.path.splitdrive(word)
_, word = os.path.split(word)
if word in (os.curdir, os.pardir):
continue
path = os.path.join(path, word)
return path
示例13: ECitMatch
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def ECitMatch(self, bdata, **kargs):
r"""
:param bdata: Citation strings. Each input citation must
be represented by a citation string in the following format::
journal_title|year|volume|first_page|author_name|your_key|
Multiple citation strings may be provided by separating the
strings with a carriage return character (%0D) or simply \\r or \\n.
The your_key value is an arbitrary label provided by the user
that may serve as a local identifier for the citation,
and it will be included in the output.
all spaces must be replaced by + symbols and that citation
strings should end with a final vertical bar |.
Only xml supported at the time of this implementation.
::
from bioservices import EUtils
s = EUtils()
print(s.ECitMatch("proc+natl+acad+sci+u+s+a|1991|88|3248|mann+bj|Art1|%0Dscience|1987|235|182|palmenberg+ac|Art2|"))
"""
# Fixes https://github.com/cokelaer/bioservices/issues/169
from urllib.parse import unquote
params = {'bdata': unquote(bdata), "retmode": "xml"}
# note here, we use .cgi not .fcgi
query = "ecitmatch.cgi?db=pubmed&retmode=xml"
ret = self.http_get(query, None, params=params)
try: ret = ret.content
except: pass
return ret
示例14: connect
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def connect(self):
netloc = unquote(urlparse(self.usbmux_socket_url).netloc)
udid, port = splitport(netloc)
if not port:
port = 8100 # WDA Default port
_device = _usbmux.device(udid)
conn = _device.create_inner_connection(int(port))
self.sock = conn._sock
self.sock.settimeout(self.timeout)
示例15: create_cookies
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def create_cookies(self, cookie):
cookies = dict()
cookies_list = cookie[0:cookie.find(';')].split("=")
cookies[cookies_list[0]] = cookies_list[1]
cookies['netcraft_js_verification_response'] = hashlib.sha1(urllib.unquote(cookies_list[1])).hexdigest()
return cookies