当前位置: 首页>>代码示例>>Python>>正文


Python CaseInsensitiveDict.keys方法代码示例

本文整理汇总了Python中requests.structures.CaseInsensitiveDict.keys方法的典型用法代码示例。如果您正苦于以下问题:Python CaseInsensitiveDict.keys方法的具体用法?Python CaseInsensitiveDict.keys怎么用?Python CaseInsensitiveDict.keys使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在requests.structures.CaseInsensitiveDict的用法示例。


在下文中一共展示了CaseInsensitiveDict.keys方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_preserve_last_key_case

# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import keys [as 别名]
 def test_preserve_last_key_case(self):
     cid = CaseInsensitiveDict({"Accept": "application/json", "user-Agent": "requests"})
     cid.update({"ACCEPT": "application/json"})
     cid["USER-AGENT"] = "requests"
     keyset = frozenset(["ACCEPT", "USER-AGENT"])
     assert frozenset(i[0] for i in cid.items()) == keyset
     assert frozenset(cid.keys()) == keyset
     assert frozenset(cid) == keyset
开发者ID:RRedwards,项目名称:requests,代码行数:10,代码来源:test_requests.py

示例2: test_preserve_key_case

# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import keys [as 别名]
 def test_preserve_key_case(self):
     cid = CaseInsensitiveDict({
         'Accept': 'application/json',
         'user-Agent': 'requests',
     })
     keyset = frozenset(['Accept', 'user-Agent'])
     assert frozenset(i[0] for i in cid.items()) == keyset
     assert frozenset(cid.keys()) == keyset
     assert frozenset(cid) == keyset
开发者ID:5x5x5x5,项目名称:try_git,代码行数:11,代码来源:test_requests.py

示例3: test_fixes_649

# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import keys [as 别名]
 def test_fixes_649(self):
     """__setitem__ should behave case-insensitively."""
     cid = CaseInsensitiveDict()
     cid["spam"] = "oneval"
     cid["Spam"] = "twoval"
     cid["sPAM"] = "redval"
     cid["SPAM"] = "blueval"
     assert cid["spam"] == "blueval"
     assert cid["SPAM"] == "blueval"
     assert list(cid.keys()) == ["SPAM"]
开发者ID:RRedwards,项目名称:requests,代码行数:12,代码来源:test_requests.py

示例4: test_preserve_last_key_case

# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import keys [as 别名]
 def test_preserve_last_key_case(self):
     cid = CaseInsensitiveDict({
         'Accept': 'application/json',
         'user-Agent': 'requests',
     })
     cid.update({'ACCEPT': 'application/json'})
     cid['USER-AGENT'] = 'requests'
     keyset = frozenset(['ACCEPT', 'USER-AGENT'])
     assert frozenset(i[0] for i in cid.items()) == keyset
     assert frozenset(cid.keys()) == keyset
     assert frozenset(cid) == keyset
开发者ID:5x5x5x5,项目名称:try_git,代码行数:13,代码来源:test_requests.py

示例5: test_preserve_key_case

# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import keys [as 别名]
 def test_preserve_key_case(self):
     cid = CaseInsensitiveDict({"Accept": "application/json", "user-Agent": "requests"})
     keyset = frozenset(["Accept", "user-Agent"])
     assert frozenset(i[0] for i in cid.items()) == keyset
     assert frozenset(cid.keys()) == keyset
     assert frozenset(cid) == keyset
开发者ID:RRedwards,项目名称:requests,代码行数:8,代码来源:test_requests.py

示例6: tizgmusicproxy

# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import keys [as 别名]

#.........这里部分代码省略.........
    def current_song_year(self):
        """ Return the current track's year of publication.

        """
        logging.info("current_song_year")
        song = self.now_playing_song
        year = 0
        if song:
            try:
                year = song['year']
                logging.info("track year %s", year)
            except KeyError:
                logging.info("year : not found")
        else:
            logging.info("current_song_year : not found")
        return year

    def clear_queue(self):
        """ Clears the playback queue.

        """
        self.queue = list()
        self.queue_index = -1

    def enqueue_artist(self, arg):
        """ Search the user's library for tracks from the given artist and adds
        them to the playback queue.

        :param arg: an artist
        """
        try:
            self.__update_local_library()
            artist = None
            if arg not in self.library.keys():
                for name, art in self.library.iteritems():
                    if arg.lower() in name.lower():
                        artist = art
                        print_wrn("[Google Play Music] '{0}' not found. " \
                                  "Playing '{1}' instead." \
                                  .format(arg.encode('utf-8'), \
                                          name.encode('utf-8')))
                        break
                if not artist:
                    # Play some random artist from the library
                    random.seed()
                    artist = random.choice(self.library.keys())
                    artist = self.library[artist]
                    print_wrn("[Google Play Music] '{0}' not found. "\
                              "Feeling lucky?." \
                              .format(arg.encode('utf-8')))
            else:
                artist = self.library[arg]
            tracks_added = 0
            for album in artist:
                tracks_added += self.__enqueue_tracks(artist[album])
            print_wrn("[Google Play Music] Playing '{0}'." \
                      .format(to_ascii(artist)))
            self.__update_play_queue_order()
        except KeyError:
            raise KeyError("Artist not found : {0}".format(arg))

    def enqueue_album(self, arg):
        """ Search the user's library for albums with a given name and adds
        them to the playback queue.

        """
开发者ID:,项目名称:,代码行数:70,代码来源:

示例7: make_request

# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import keys [as 别名]
    def make_request(self, method, bucket, key=None, params=None, data=None,
                     headers=None):
        # Remove params that are set to None
        if isinstance(params, dict):
            for k, v in params.copy().items():
                if v is None:
                    params.pop(k)

        # Construct target url
        url = 'http://{}.{}'.format(bucket, self.hostname)
        url += '/{}'.format(key) if key is not None else '/'
        if isinstance(params, dict) and len(params) > 0:
            url += '?{}'.format(urllib.urlencode(params))
        elif isinstance(params, basestring):
            url += '?{}'.format(params)

        # Make headers case insensitive
        if headers is None:
            headers = {}
        headers = CaseInsensitiveDict(headers)

        headers['Host'] = '{}.{}'.format(bucket, self.hostname)

        if data is not None:
            try:
                raw_md5 = utils.f_md5(data)
            except:
                m = hashlib.md5()
                m.update(data)
                raw_md5 = m.digest()
            md5 = b64encode(raw_md5)
            headers['Content-MD5'] = md5
        else:
            md5 = ''

        try:
            content_type = headers['Content-Type']
        except KeyError:
            content_type = ''

        date = formatdate(timeval=None, localtime=False, usegmt=True)
        headers['x-amz-date'] = date

        # Construct canonicalized amz headers string
        canonicalized_amz_headers = ''
        amz_keys = [k for k in list(headers.keys()) if k.startswith('x-amz-')]
        for k in sorted(amz_keys):
            v = headers[k].strip()
            canonicalized_amz_headers += '{}:{}\n'.format(k.lower(), v)

        # Construct canonicalized resource string
        canonicalized_resource = '/' + bucket
        canonicalized_resource += '/' if key is None else '/{}'.format(key)
        if isinstance(params, basestring):
            canonicalized_resource += '?{}'.format(params)
        elif isinstance(params, dict) and len(params) > 0:
            canonicalized_resource += '?{}'.format(urllib.urlencode(params))

        # Construct string to sign
        string_to_sign = method.upper() + '\n'
        string_to_sign += md5 + '\n'
        string_to_sign += content_type + '\n'
        string_to_sign += '\n'  # date is always set through x-amz-date
        string_to_sign += canonicalized_amz_headers + canonicalized_resource

        # Create signature
        h = hmac.new(self.secret_access_key, string_to_sign, hashlib.sha1)
        signature = b64encode(h.digest())

        # Set authorization header
        auth_head = 'AWS {}:{}'.format(self.access_key_id, signature)
        headers['Authorization'] = auth_head

        # Prepare Request
        req = Request(method, url, data=data, headers=headers).prepare()

        # Log request data.
        # Prepare request beforehand so requests-altered headers show.
        # Combine into a single message so we don't have to bother with
        # locking to make lines appear together.
        log_message = '{} {}\n'.format(method, url)
        log_message += 'headers:'
        for k in sorted(req.headers.keys()):
            log_message += '\n {}: {}'.format(k, req.headers[k])
        log.debug(log_message)

        # Send request
        resp = Session().send(req)

        # Update stats, log response data.
        self.stats[method.upper()] += 1
        log.debug('response: {} ({} {})'.format(resp.status_code, method, url))

        # Handle errors
        if resp.status_code/100 != 2:
            soup = BeautifulSoup(resp.text)
            error = soup.find('error')

            log_message = "S3 replied with non 2xx response code!!!!\n"
            log_message += '  request: {} {}\n'.format(method, url)
#.........这里部分代码省略.........
开发者ID:viglesiasce,项目名称:s3tup,代码行数:103,代码来源:connection.py

示例8: tizgmusicproxy

# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import keys [as 别名]
class tizgmusicproxy(object):
    """A class for accessing a Google Music account to retrieve song URLs.
    """

    all_songs_album_title = "All Songs"
    thumbs_up_playlist_name = "Thumbs Up"

    def __init__(self, email, password, device_id):
        self.__api = Mobileclient()
        self.logged_in = False
        self.__device_id = device_id
        self.queue = list()
        self.queue_index = -1
        self.play_mode = 0
        self.now_playing_song = None

        attempts = 0
        while not self.logged_in and attempts < 3:
            self.logged_in = self.__api.login(email, password)
            attempts += 1

        self.playlists = CaseInsensitiveDict()
        self.library = CaseInsensitiveDict()

    def logout(self):
        self.__api.logout()

    def update_local_lib(self):
        songs = self.__api.get_all_songs()
        self.playlists[self.thumbs_up_playlist_name] = list()

        # Get main library
        song_map = dict()
        for song in songs:
            if "rating" in song and song["rating"] == "5":
                self.playlists[self.thumbs_up_playlist_name].append(song)

            song_id = song["id"]
            song_artist = song["artist"]
            song_album = song["album"]

            song_map[song_id] = song

            if song_artist == "":
                song_artist = "Unknown Artist"

            if song_album == "":
                song_album = "Unknown Album"

            if not (song_artist in self.library):
                self.library[song_artist] = dict()
                self.library[song_artist][self.all_songs_album_title] = list()

            if not (song_album in self.library[song_artist]):
                self.library[song_artist][song_album] = list()

            self.library[song_artist][song_album].append(song)
            self.library[song_artist][self.all_songs_album_title].append(song)

        # Sort albums by track number
        for artist in self.library.keys():
            logging.info("Artist : {0}".format(artist.encode("utf-8")))
            for album in self.library[artist].keys():
                logging.info("   Album : {0}".format(album.encode("utf-8")))
                if album == self.all_songs_album_title:
                    sorted_album = sorted(self.library[artist][album], key=lambda k: k["title"])
                else:
                    sorted_album = sorted(self.library[artist][album], key=lambda k: k.get("trackNumber", 0))
                self.library[artist][album] = sorted_album

        # Get all playlists
        plists = self.__api.get_all_user_playlist_contents()
        for plist in plists:
            plist_name = plist["name"]
            self.playlists[plist_name] = list()
            for track in plist["tracks"]:
                try:
                    song = song_map[track["trackId"]]
                    self.playlists[plist_name].append(song)
                except IndexError:
                    pass

    def current_song_title_and_artist(self):
        logging.info("current_song_title_and_artist")
        song = self.now_playing_song
        if song is not None:
            title = self.now_playing_song["title"]
            artist = self.now_playing_song["artist"]
            logging.info("Now playing {0} by {1}".format(title.encode("utf-8"), artist.encode("utf-8")))
            return artist.encode("utf-8"), title.encode("utf-8")
        else:
            return "", ""

    def current_song_album_and_duration(self):
        logging.info("current_song_album_and_duration")
        song = self.now_playing_song
        if song is not None:
            album = self.now_playing_song["album"]
            duration = self.now_playing_song["durationMillis"]
            logging.info("album {0} duration {1}".format(album.encode("utf-8"), duration.encode("utf-8")))
#.........这里部分代码省略.........
开发者ID:commshare,项目名称:tizonia-openmax-il,代码行数:103,代码来源:tizgmusicproxy.py


注:本文中的requests.structures.CaseInsensitiveDict.keys方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。