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


Python tokencache.TokenCache類代碼示例

本文整理匯總了Python中flickrapi.tokencache.TokenCache的典型用法代碼示例。如果您正苦於以下問題:Python TokenCache類的具體用法?Python TokenCache怎麽用?Python TokenCache使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了TokenCache類的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_username

    def test_username(self):
        """Username should impact the location of the cache on disk."""

        from flickrapi.tokencache import TokenCache

        user_tc = TokenCache(u'123-456', username=u'frøbel', path=self.tc_path)

        tc_path = self.tc.get_cached_token_filename()
        user_path = user_tc.get_cached_token_filename()

        self.assertNotEquals(tc_path, user_path)
        self.assertNotIn(u'frøbel', tc_path)
        self.assertIn(u'frøbel', user_path)
開發者ID:sybrenstuvel,項目名稱:flickrapi,代碼行數:13,代碼來源:test_tokencache.py

示例2: TokenCacheTest

class TokenCacheTest(unittest.TestCase):
    def setUp(self):
        import tempfile
        from flickrapi.tokencache import TokenCache

        # Use mkdtemp() for backward compatibility with Python 2.7
        self.tc_path = tempfile.mkdtemp()
        self.tc = TokenCache('123-456', path=self.tc_path)

    def tearDown(self):
        tc_path = getattr(self, 'tc_path', None)
        if tc_path is not None:
            import shutil
            shutil.rmtree(self.tc_path)

    def test_get_set_del(self):
        self.assertIsNone(self.tc.token)

        # Check setting token, both in memory and on disk.
        self.tc.token = u'nümbér'
        self.assertEquals(self.tc.token, u'nümbér')
        on_disk = open(self.tc.get_cached_token_filename(), 'rb').read()
        self.assertEquals(on_disk.decode('utf8'), u'nümbér')

        # Erase from in-RAM cache and try again, to read from disk.
        self.tc.memory.clear()
        self.assertEquals(self.tc.token, u'nümbér')

        del self.tc.token
        self.assertIsNone(self.tc.token)

        self.tc.token = u'nümbér'
        self.tc.forget()
        self.assertIsNone(self.tc.token)

    def test_username(self):
        """Username should impact the location of the cache on disk."""

        from flickrapi.tokencache import TokenCache

        user_tc = TokenCache(u'123-456', username=u'frøbel', path=self.tc_path)

        tc_path = self.tc.get_cached_token_filename()
        user_path = user_tc.get_cached_token_filename()

        self.assertNotEquals(tc_path, user_path)
        self.assertNotIn(u'frøbel', tc_path)
        self.assertIn(u'frøbel', user_path)
開發者ID:sybrenstuvel,項目名稱:flickrapi,代碼行數:48,代碼來源:test_tokencache.py

示例3: setUp

    def setUp(self):
        import tempfile
        from flickrapi.tokencache import TokenCache

        # Use mkdtemp() for backward compatibility with Python 2.7
        self.tc_path = tempfile.mkdtemp()
        self.tc = TokenCache('123-456', path=self.tc_path)
開發者ID:sybrenstuvel,項目名稱:flickrapi,代碼行數:7,代碼來源:test_tokencache.py

示例4: __init__

 def __init__(self, apiKey, secret=None, fail_on_error=True):
     """Construct a new FlickrAPI instance for a given API key and secret."""
     
     self.apiKey = apiKey
     self.secret = secret
     self.token_cache = TokenCache(apiKey)
     self.token = self.token_cache.token
     self.fail_on_error = fail_on_error
     
     self.__handlerCache={}
開發者ID:syncopated,項目名稱:97bottles,代碼行數:10,代碼來源:__init__.py

示例5: __init__

    def __init__(self, api_key, secret=None, fail_on_error=True,
                 username=None, token=None):
        """Construct a new FlickrAPI instance for a given API key
        and secret.
        
        api_key
            The API key as obtained from Flickr
        
        secret
            The secret belonging to the API key
        
        fail_on_error
            If False, errors won't be checked by the FlickrAPI module.
            True by default, of course.
        
        username
            Used to identify the appropriate authentication token for a
            certain user.
        
        token
            If you already have an authentication token, you can give
            it here. It won't be stored on disk by the FlickrAPI instance
        
        """
        
        self.api_key = api_key
        self.secret = secret
        self.fail_on_error = fail_on_error
        
        self.__handler_cache = {}

        if token:
            # Use a memory-only token cache
            self.token_cache = SimpleTokenCache()
            self.token_cache.token = token
        else:
            # Use a real token cache
            self.token_cache = TokenCache(api_key, username)
開發者ID:dchest,項目名稱:acorn-flickr-export,代碼行數:38,代碼來源:__init__.py

示例6: __init__

    def __init__(self, api_key, secret=None, username=None,
            token=None, format='etree', store_token=True,
            cache=False):
        """Construct a new FlickrAPI instance for a given API key
        and secret.
        
        api_key
            The API key as obtained from Flickr.
        
        secret
            The secret belonging to the API key.
        
        username
            Used to identify the appropriate authentication token for a
            certain user.
        
        token
            If you already have an authentication token, you can give
            it here. It won't be stored on disk by the FlickrAPI instance.

        format
            The response format. Use either "xmlnode" or "etree" to get a parsed
            response, or use any response format supported by Flickr to get an
            unparsed response from method calls. It's also possible to pass the
            ``format`` parameter on individual calls.

        store_token
            Disables the on-disk token cache if set to False (default is True).
            Use this to ensure that tokens aren't read nor written to disk, for
            example in web applications that store tokens in cookies.

        cache
            Enables in-memory caching of FlickrAPI calls - set to ``True`` to
            use. If you don't want to use the default settings, you can
            instantiate a cache yourself too:

            >>> f = FlickrAPI(api_key='123')
            >>> f.cache = SimpleCache(timeout=5, max_entries=100)
        """
        
        self.api_key = api_key
        self.secret = secret
        self.default_format = format
        
        self.__handler_cache = {}

        if token:
            # Use a memory-only token cache
            self.token_cache = SimpleTokenCache()
            self.token_cache.token = token
        elif not store_token:
            # Use an empty memory-only token cache
            self.token_cache = SimpleTokenCache()
        else:
            # Use a real token cache
            self.token_cache = TokenCache(api_key, username)

        if cache:
            self.cache = SimpleCache()
        else:
            self.cache = None
開發者ID:hongseokyoon,項目名稱:SimplyFlickr,代碼行數:61,代碼來源:__init__.py

示例7: FlickrAPI

class FlickrAPI(object):
    """Encapsulates Flickr functionality.
    
    Example usage::
      
      flickr = flickrapi.FlickrAPI(api_key)
      photos = flickr.photos_search(user_id='[email protected]', per_page='10')
      sets = flickr.photosets_getList(user_id='[email protected]')
    """
    
    flickr_host = "api.flickr.com"
    flickr_rest_form = "/services/rest/"
    flickr_auth_form = "/services/auth/"
    flickr_upload_form = "/services/upload/"
    flickr_replace_form = "/services/replace/"

    def __init__(self, api_key, secret=None, username=None,
            token=None, format='etree', store_token=True,
            cache=False):
        """Construct a new FlickrAPI instance for a given API key
        and secret.
        
        api_key
            The API key as obtained from Flickr.
        
        secret
            The secret belonging to the API key.
        
        username
            Used to identify the appropriate authentication token for a
            certain user.
        
        token
            If you already have an authentication token, you can give
            it here. It won't be stored on disk by the FlickrAPI instance.

        format
            The response format. Use either "xmlnode" or "etree" to get a parsed
            response, or use any response format supported by Flickr to get an
            unparsed response from method calls. It's also possible to pass the
            ``format`` parameter on individual calls.

        store_token
            Disables the on-disk token cache if set to False (default is True).
            Use this to ensure that tokens aren't read nor written to disk, for
            example in web applications that store tokens in cookies.

        cache
            Enables in-memory caching of FlickrAPI calls - set to ``True`` to
            use. If you don't want to use the default settings, you can
            instantiate a cache yourself too:

            >>> f = FlickrAPI(api_key='123')
            >>> f.cache = SimpleCache(timeout=5, max_entries=100)
        """
        
        self.api_key = api_key
        self.secret = secret
        self.default_format = format
        
        self.__handler_cache = {}

        if token:
            # Use a memory-only token cache
            self.token_cache = SimpleTokenCache()
            self.token_cache.token = token
        elif not store_token:
            # Use an empty memory-only token cache
            self.token_cache = SimpleTokenCache()
        else:
            # Use a real token cache
            self.token_cache = TokenCache(api_key, username)

        if cache:
            self.cache = SimpleCache()
        else:
            self.cache = None

    def __repr__(self):
        '''Returns a string representation of this object.'''


        return '[FlickrAPI for key "%s"]' % self.api_key
    __str__ = __repr__

    def trait_names(self):
        '''Returns a list of method names as supported by the Flickr
        API. Used for tab completion in IPython.
        '''

        try:
            rsp = self.reflection_getMethods(format='etree')
        except FlickrError:
            return None

        def tr(name):
            '''Translates Flickr names to something that can be called
            here.

            >>> tr(u'flickr.photos.getInfo')
#.........這裏部分代碼省略.........
開發者ID:hongseokyoon,項目名稱:SimplyFlickr,代碼行數:101,代碼來源:__init__.py

示例8: FlickrAPI

class FlickrAPI:
    """Encapsulated flickr functionality.

    Example usage:

      flickr = FlickrAPI(flickrAPIKey, flickrSecret)
      rsp = flickr.auth_checkToken(api_key=flickrAPIKey, auth_token=token)

    """
    
    flickrHost = "api.flickr.com"
    flickrRESTForm = "/services/rest/"
    flickrAuthForm = "/services/auth/"
    flickrUploadForm = "/services/upload/"
    flickrReplaceForm = "/services/replace/"

    #-------------------------------------------------------------------
    def __init__(self, apiKey, secret=None, fail_on_error=True):
        """Construct a new FlickrAPI instance for a given API key and secret."""
        
        self.apiKey = apiKey
        self.secret = secret
        self.token_cache = TokenCache(apiKey)
        self.token = self.token_cache.token
        self.fail_on_error = fail_on_error
        
        self.__handlerCache={}

    def __repr__(self):
        return '[FlickrAPI for key "%s"]' % self.apiKey
    __str__ = __repr__
    
    #-------------------------------------------------------------------
    def sign(self, dictionary):
        """Calculate the flickr signature for a set of params.

        data -- a hash of all the params and values to be hashed, e.g.
                {"api_key":"AAAA", "auth_token":"TTTT", "key": u"value".encode('utf-8')}

        """

        data = [self.secret]
        keys = dictionary.keys()
        keys.sort()
        for key in keys:
            data.append(key)
            datum = dictionary[key]
            if isinstance(datum, unicode):
                raise IllegalArgumentException("No Unicode allowed, "
                        "argument %s (%r) should have been UTF-8 by now"
                        % (key, datum))
            data.append(datum)
        
        md5_hash = md5.new()
        md5_hash.update(''.join(data))
        return md5_hash.hexdigest()

    def encode_and_sign(self, dictionary):
        '''URL encodes the data in the dictionary, and signs it using the
        given secret, if a secret was given.
        '''
        
        dictionary = self.make_utf8(dictionary)
        if self.secret:
            dictionary['api_sig'] = self.sign(dictionary)
        return urllib.urlencode(dictionary)
        
    def make_utf8(self, dictionary):
        '''Encodes all Unicode strings in the dictionary to UTF-8. Converts
        all other objects to regular strings.
        
        Returns a copy of the dictionary, doesn't touch the original.
        '''
        
        result = {}

        for (key, value) in dictionary.iteritems():
            if isinstance(value, unicode):
                value = value.encode('utf-8')
            else:
                value = str(value)
            result[key] = value
        
        return result
        
    #-------------------------------------------------------------------
    def __getattr__(self, method):
        """Handle all the regular Flickr API calls.

        >>> flickr.auth_getFrob(apiKey="AAAAAA")
        >>> xmlnode = flickr.photos_getInfo(photo_id='1234')
        >>> json = flickr.photos_getInfo(photo_id='1234', format='json')
        """

        # Refuse to act as a proxy for unimplemented special methods
        if method.startswith('__'):
            raise AttributeError("No such attribute '%s'" % method)

        if self.__handlerCache.has_key(method):
            # If we already have the handler, return it
#.........這裏部分代碼省略.........
開發者ID:syncopated,項目名稱:97bottles,代碼行數:101,代碼來源:__init__.py

示例9: __init__

class FlickrAPI:
    """Encapsulates Flickr functionality.
    
    Example usage::
      
      flickr = flickrapi.FlickrAPI(api_key)
      photos = flickr.photos_search(user_id='[email protected]', per_page='10')
      sets = flickr.photosets_getList(user_id='[email protected]')
    """
    
    flickr_host = "api.flickr.com"
    flickr_rest_form = "/services/rest/"
    flickr_auth_form = "/services/auth/"
    flickr_upload_form = "/services/upload/"
    flickr_replace_form = "/services/replace/"

    def __init__(self, api_key, secret=None, fail_on_error=None, username=None,
            token=None, format='xmlnode', store_token=True, cache=False):
        """Construct a new FlickrAPI instance for a given API key
        and secret.
        
        api_key
            The API key as obtained from Flickr.
        
        secret
            The secret belonging to the API key.
        
        fail_on_error
            If False, errors won't be checked by the FlickrAPI module.
            Deprecated, don't use this parameter, just handle the FlickrError
            exceptions.
        
        username
            Used to identify the appropriate authentication token for a
            certain user.
        
        token
            If you already have an authentication token, you can give
            it here. It won't be stored on disk by the FlickrAPI instance.

        format
            The response format. Use either "xmlnode" or "etree" to get a parsed
            response, or use any response format supported by Flickr to get an
            unparsed response from method calls. It's also possible to pass the
            ``format`` parameter on individual calls.

        store_token
            Disables the on-disk token cache if set to False (default is True).
            Use this to ensure that tokens aren't read nor written to disk, for
            example in web applications that store tokens in cookies.

        cache
            Enables in-memory caching of FlickrAPI calls - set to ``True`` to
            use. If you don't want to use the default settings, you can
            instantiate a cache yourself too:

            >>> f = FlickrAPI(api_key='123')
            >>> f.cache = SimpleCache(timeout=5, max_entries=100)
        """
        
        if fail_on_error is not None:
            LOG.warn("fail_on_error has been deprecated. Remove this "
                     "parameter and just handle the FlickrError exceptions.")
        else:
            fail_on_error = True

        self.api_key = api_key
        self.secret = secret
        self.fail_on_error = fail_on_error
        self.default_format = format
        
        self.__handler_cache = {}

        if token:
            # Use a memory-only token cache
            self.token_cache = SimpleTokenCache()
            self.token_cache.token = token
        elif not store_token:
            # Use an empty memory-only token cache
            self.token_cache = SimpleTokenCache()
        else:
            # Use a real token cache
            self.token_cache = TokenCache(api_key, username)

        if cache:
            self.cache = SimpleCache()
        else:
            self.cache = None

    def __repr__(self):
        '''Returns a string representation of this object.'''


        return '[FlickrAPI for key "%s"]' % self.api_key
    __str__ = __repr__

    def trait_names(self):
        '''Returns a list of method names as supported by the Flickr
        API. Used for tab completion in IPython.
        '''
#.........這裏部分代碼省略.........
開發者ID:arsfeld,項目名稱:conduit,代碼行數:101,代碼來源:__init__.py


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