當前位置: 首頁>>代碼示例>>Python>>正文


Python request.unquote方法代碼示例

本文整理匯總了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 
開發者ID:tomduck,項目名稱:pandoc-fignos,代碼行數:27,代碼來源:pandoc_fignos.py

示例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) 
開發者ID:pyconjp,項目名稱:pyconjpbot,代碼行數:28,代碼來源:google.py

示例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) 
開發者ID:llimllib,項目名稱:limbo,代碼行數:17,代碼來源:google.py

示例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) 
開發者ID:dominodatalab,項目名稱:python-domino,代碼行數:13,代碼來源:domino.py

示例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 
開發者ID:justdoit0823,項目名稱:pywxclient,代碼行數:9,代碼來源:utils.py

示例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 
開發者ID:spinnaker,項目名稱:spinnaker-monitoring,代碼行數:15,代碼來源:http_server.py

示例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(' ')) 
開發者ID:declension,項目名稱:squeeze-alexa,代碼行數:4,代碼來源:server.py

示例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] 
開發者ID:declension,項目名稱:squeeze-alexa,代碼行數:11,代碼來源:server.py

示例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 
開發者ID:riag,項目名稱:manjaro-linux-for-wsl,代碼行數:62,代碼來源:manjaro-bootstrap.py

示例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 '' 
開發者ID:jurialmunkey,項目名稱:plugin.video.themoviedb.helper,代碼行數:56,代碼來源:service.py

示例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_() 
開發者ID:FrancescoCeruti,項目名稱:linux-show-player,代碼行數:48,代碼來源:media_info.py

示例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) 
開發者ID:mostafa,項目名稱:grest,代碼行數:49,代碼來源:validation.py


注:本文中的urllib.request.unquote方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。