本文整理汇总了Python中urllib.request.unquote方法的典型用法代码示例。如果您正苦于以下问题:Python request.unquote方法的具体用法?Python request.unquote怎么用?Python request.unquote使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类urllib.request
的用法示例。
在下文中一共展示了request.unquote方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _extract_attrs
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import unquote [as 别名]
def _extract_attrs(x, n):
"""Extracts attributes for an image in the element list `x`. The
attributes begin at index `n`. Extracted elements are deleted
from the list.
"""
try: # Try the standard call from pandocxnos first
return extract_attrs(x, n)
except (ValueError, IndexError):
if PANDOCVERSION < '1.16':
# Look for attributes attached to the image path, as occurs with
# image references for pandoc < 1.16 (pandoc-fignos Issue #14).
# See http://pandoc.org/MANUAL.html#images for the syntax.
# Note: This code does not handle the "optional title" for
# image references (search for link_attributes in pandoc's docs).
assert x[n-1]['t'] == 'Image'
image = x[n-1]
s = image['c'][-1][0]
if '%20%7B' in s:
path = s[:s.index('%20%7B')]
attrstr = unquote(s[s.index('%7B'):])
image['c'][-1][0] = path # Remove attr string from the path
return PandocAttributes(attrstr.strip(), 'markdown')
raise
示例2: google
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import unquote [as 别名]
def google(message, keywords):
"""
google で検索した結果を返す
https://github.com/llimllib/limbo/blob/master/limbo/plugins/google.py
"""
if keywords == 'help':
return
query = quote(keywords)
url = "https://encrypted.google.com/search?q={0}".format(query)
soup = BeautifulSoup(requests.get(url).text, "html.parser")
answer = soup.findAll("h3", attrs={"class": "r"})
if not answer:
botsend(message, "`{}` での検索結果はありませんでした".format(keywords))
try:
_, url = answer[0].a['href'].split('=', 1)
url, _ = url.split('&', 1)
botsend(message, unquote(url))
except IndexError:
# in this case there is a first answer without a link, which is a
# google response! Let's grab it and display it to the user.
return ' '.join(answer[0].stripped_strings)
示例3: google
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import unquote [as 别名]
def google(q):
query = quote(q)
url = "https://encrypted.google.com/search?q={0}".format(query)
soup = BeautifulSoup(requests.get(url).text, "html5lib")
answer = soup.findAll("h3", attrs={"class": "r"})
if not answer:
return ":crying_cat_face: Sorry, google doesn't have an answer for you :crying_cat_face:"
try:
return unquote(re.findall(r"q=(.*?)&", str(answer[0]))[0])
except IndexError:
# in this case there is a first answer without a link, which is a
# google response! Let's grab it and display it to the user.
return ' '.join(answer[0].stripped_strings)
示例4: parse_play_flash_cookie
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import unquote [as 别名]
def parse_play_flash_cookie(response):
flash_cookie = response.cookies['PLAY_FLASH']
messageType, message = flash_cookie.split("=")
# Format message into user friendly string
message = urllib2.unquote(message).replace("+", " ")
# Discern error disposition
if (messageType == "dominoFlashError"):
error = True
else:
error = False
return dict(messageType=messageType, message=message, error=error)
示例5: parse_new_login_page
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import unquote [as 别名]
def parse_new_login_page(cls, res_xml):
"""Parse new login page xml response."""
data = xml2dict(res_xml)['error']
if 'pass_ticket' in data:
data['pass_ticket'] = unquote(data['pass_ticket'])
return data
示例6: decode_request
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import unquote [as 别名]
def decode_request(self, request):
"""Extract the URL components from the request."""
parameters = {}
path, _, query = request.partition('?')
if not query:
return request, parameters, None
query, _, fragment = query.partition('#')
for part in query.split('&'):
key, _, value = part.partition('=')
parameters[key] = urllibUnquote(value)
return path, parameters, fragment or None
示例7: _unquote
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import unquote [as 别名]
def _unquote(self, response):
return ' '.join(urllib.unquote(s) for s in response.split(' '))
示例8: __pairs_from
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import unquote [as 别名]
def __pairs_from(self, response):
"""Split and unescape a response"""
def demunge(string):
s = urllib.unquote(string)
return tuple(s.split(':', 1))
demunged = map(demunge, response.split(' '))
return [d for d in demunged if len(d) == 2]
示例9: fetch_packages
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import unquote [as 别名]
def fetch_packages(context: BootstrapContext):
path = os.path.join(context.work_dir, 'core.packages.json')
if os.path.isfile(path) and not file_is_outofday(context, path):
with io.open(path, 'r', encoding='utf-8') as f:
d = json.load(f)
m = {}
for k, v in d.items():
m[k] = PackageInfo(**v)
context.core_package_map = m
return m
output = fetch(context)
sio = io.StringIO(output)
package_map = {}
for line in sio:
if not line:
continue
match = core_repo_package_pattern.search(line)
if match is None:
continue
package = match.group(1)
if package in ignore_package:
continue
if package.endswith('.sig'):
continue
package = request.unquote(package)
match = package_name_pattern.search(package)
if match is None:
print("cannot parse package name %s" % package)
sys.exit(-1)
name = match.group(1)
version = match.group(2)
match = package_update_time_pattern.search(line)
if match is None:
print("cannot parse package update time, line is %s" % line)
sys.exit(-1)
update_time_str = match.group(1)
update_time = datetime.datetime.strptime(
update_time_str, update_time_fmt
)
t = package_map.get(name, None)
if t is not None and version < t.version:
continue
p = PackageInfo(name, version, package)
package_map[name] = p
with io.open(path, 'w', encoding='utf-8') as f:
m = {}
for k, v in package_map.items():
m[k] = v.to_map()
json.dump(m, f)
context.core_package_map = package_map
return package_map
示例10: _openimage
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import unquote [as 别名]
def _openimage(image, targetpath, filename):
""" Open image helper with thanks to sualfred """
# some paths require unquoting to get a valid cached thumb hash
cached_image_path = urllib.unquote(image.replace('image://', ''))
if cached_image_path.endswith('/'):
cached_image_path = cached_image_path[:-1]
cached_files = []
for path in [xbmc.getCacheThumbName(cached_image_path), xbmc.getCacheThumbName(image)]:
cached_files.append(os.path.join('special://profile/Thumbnails/', path[0], path[:-4] + '.jpg'))
cached_files.append(os.path.join('special://profile/Thumbnails/', path[0], path[:-4] + '.png'))
cached_files.append(os.path.join('special://profile/Thumbnails/Video/', path[0], path))
for i in range(1, 4):
try:
''' Try to get cached image at first
'''
for cache in cached_files:
if xbmcvfs.exists(cache):
try:
img = Image.open(xbmc.translatePath(cache))
return img
except Exception as error:
utils.kodi_log('Image error: Could not open cached image --> %s' % error, 2)
''' Skin images will be tried to be accessed directly. For all other ones
the source will be copied to the addon_data folder to get access.
'''
if xbmc.skinHasImage(image):
if not image.startswith('special://skin'):
image = os.path.join('special://skin/media/', image)
try: # in case image is packed in textures.xbt
img = Image.open(xbmc.translatePath(image))
return img
except Exception:
return ''
else:
targetfile = os.path.join(targetpath, filename)
if not xbmcvfs.exists(targetfile):
xbmcvfs.copy(image, targetfile)
img = Image.open(targetfile)
return img
except Exception as error:
utils.kodi_log('Image error: Could not get image for %s (try %d) -> %s' % (image, i, error), 2)
xbmc.sleep(500)
pass
return ''
示例11: show_info
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import unquote [as 别名]
def show_info(self, clicked):
media_uri = Application().layout.get_context_cue().media.input_uri()
if not media_uri:
QMessageBox.critical(MainWindow(), translate('MediaInfo', 'Error'),
translate('MediaInfo', 'No info to display'))
else:
gst_info = gst_uri_metadata(media_uri)
info = {'URI': unquote(gst_info.get_uri())}
# Audio streams info
for stream in gst_info.get_audio_streams():
name = stream.get_stream_type_nick().capitalize()
info[name] = {
'Bitrate': str(stream.get_bitrate() // 1000) + ' Kb/s',
'Channels': str(stream.get_channels()),
'Sample rate': str(stream.get_sample_rate()) + ' Hz',
'Sample size': str(stream.get_depth()) + ' bit'
}
# Video streams info
for stream in gst_info.get_video_streams():
name = stream.get_stream_type_nick().capitalize()
info[name] = {
'Height': str(stream.get_height()) + ' px',
'Width': str(stream.get_width()) + ' px',
'Framerate': str(round(stream.get_framerate_num() /
stream.get_framerate_denom()))
}
# Media tags
info['Tags'] = {}
tags = gst_info.get_tags()
if tags is not None:
tags = gst_parse_tags_list(tags)
for tag in tags:
if type(tags[tag]).__str__ is not object.__str__:
info['Tags'][tag.capitalize()] = str(tags[tag])
if not info['Tags']:
info.pop('Tags')
# Show the dialog
dialog = InfoDialog(MainWindow(), info,
Application().layout.get_context_cue().name)
dialog.exec_()
示例12: validate_models
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import unquote [as 别名]
def validate_models(self,
primary_id=None,
secondary_model_name=None,
secondary_id=None):
class Primary:
id = None
model = None
model_name = None
selection_field = None
class Secondary:
id = None
model = None
model_name = None
selection_field = None
if primary_id:
Primary.id = escape(unquote(primary_id))
Primary.model = self.__model__.get("primary")
Primary.model_name = Primary.model.__name__.lower()
Primary.selection_field = self.__selection_field__.get("primary")
if secondary_model_name:
Secondary.model_name = escape(unquote(secondary_model_name))
if secondary_id:
Secondary.id = escape(unquote(secondary_id))
Secondary.model = Secondary.selection_field = None
if "secondary" in self.__model__:
Secondary.model = self.__model__.get(
"secondary").get(Secondary.model_name)
if "secondary" in self.__selection_field__:
Secondary.selection_fields = self.__selection_field__.get(
"secondary")
Secondary.selection_field = Secondary.selection_fields.get(
Secondary.model_name)
if all([Secondary.model_name is not None,
Secondary.model is None]):
raise HTTPException(msg.RELATION_DOES_NOT_EXIST, 404)
return (Primary, Secondary)