Skip to content

File caching for the oauth2client >= 4.0.0  #325

Closed

Description

@xmedeko

@tmatsuo proposed in #110 to cache discovery.build(), however, #294 has stopped using cache outside of the GAE (appengine) environment (see also #299). E.g. the discovery.build() is not cached in the CGE environment. Is it possible to bring the file caching back, or provide some example of file cache (subclass of googleapiclient.discovery_cache.Cache)?

Activity

  1. theacodes commented on Jan 9, 2017

    @theacodes
    Contributor
  2. Schweigi commented on Jan 22, 2017

    @Schweigi

    Is there a known workaround in the meantime?

  3. Schweigi commented on Jan 22, 2017

    @Schweigi

    I created a small workaround by using a in memory cache (see example below). Does anyone know if there should be a regular cache invalidation? Currently the memory cache is cleared on each deployment, I hope that's ok for the time being.

    In memory cache:

    class MemoryCache(Cache):
        _CACHE = {}
    
        def get(self, url):
            return MemoryCache._CACHE.get(url)
    
        def set(self, url, content):
            MemoryCache._CACHE[url] = content
    

    Usage:

    http = ...
    service = discovery.build('calendar', 'v3', http=http, cache=MemoryCache())
    
  4. xmedeko commented on Jan 23, 2017

    @xmedeko
    ContributorAuthor

    AFAIK the Google production API should not change (the same version of API), so the you do not need to invalidate the cache. However, the discovery_cache/__init__.py defines the limit DISCOVERY_DOC_MAX_AGE as one day.

    +1 for a neat, simple MemoryCache. IMO it's good when you have a single, long running process.

    If you want to share the cache among processes, (like running scripts by the cron,) you may copy the old good oauth2client locked_file.py and then to plug it somehow with discovery_cache/file_cache.py. Beware, the locked_file.py is considered not 100% save, so you take the risk. (But works well in practice.) By "plugin somehow" I mean either copy & change the discovery_cache/file_cache.py to take your locked_file.py or to trick the Python to think your locked_file.py is from the oauth2client.locked_file package.

  5. xmedeko commented on May 17, 2017

    @xmedeko
    ContributorAuthor

    @jonparrott what about to change file lock to the multiprocessing.RLock() in the original locked_file.py? Would be it sufficient solution to accept back to the repo?

  6. theacodes commented on May 17, 2017

    @theacodes
    Contributor
  7. xmedeko commented on May 17, 2017

    @xmedeko
    ContributorAuthor

    You mean a file cache, shared among multiple processes, without any locking? How to prevent data corruption, when 2 process write to the same file?

  8. theacodes commented on May 17, 2017

    @theacodes
    Contributor
  9. removed their assignment
    on Oct 10, 2017
  10. added
    🚨
    type: feature request
    and removed on Jun 8, 2018
  11. 3 remaining items

  12. Chronial commented on Sep 7, 2018

    @Chronial

    Based on Schweigi's solution, I wrote a simple file based cache (unix-only) to also cache across processes.

    import os.path
    import hashlib
    import tempfile
    
    class DiscoveryCache:
        def filename(self, url):
            return os.path.join(
                tempfile.gettempdir(),
                'google_api_discovery_' + hashlib.md5(url.encode()).hexdigest())
    
        def get(self, url):
            try:
                with open(self.filename(url), 'rb') as f:
                    return f.read().decode()
            except FileNotFoundError:
                return None
    
        def set(self, url, content):
            with tempfile.NamedTemporaryFile(delete=False) as f:
                f.write(content.encode())
                f.flush()
                os.fsync(f)
            os.rename(f.name, self.filename(url))
  13. removed
    🚨
    priority: p2
    on Feb 5, 2019
  14. busunkim96 commented on Jun 10, 2019

    @busunkim96
    Contributor

    I'm opting to close this as it's unlikely we will implement it in the future.

    These client libraries are officially supported by Google. However, the libraries are considered complete and are in maintenance mode. This means that we will address critical bugs and security issues but will not add any new features.

  15. added a commit that references this issue on Feb 2, 2020
  16. added a commit that references this issue on Feb 25, 2020
  17. aawilson commented on Jun 26, 2020

    @aawilson

    I don't know if this changed at some point, but I had to import Cache from googleapiclient.discovery_cache.base (presumably googleapiclient.discovery_cache.file_cache also works fine, but inheriting from the Base class is almost certainly the better idea)

  18. Kache commented on Sep 20, 2021

    @Kache

    An equivalent & simpler workaround is to set cache_discovery=False:

    discovery.build(api, version, http=http, cache_discovery=False)

    Since according to the source the "cache" is never reused in the "single, long running process" case.

  19. neomafo88 commented on Nov 27, 2022

    @neomafo88

    I created a small workaround by using a in memory cache (see example below). Does anyone know if there should be a regular cache invalidation? Currently the memory cache is cleared on each deployment, I hope that's ok for the time being.

    In memory cache:

    class MemoryCache(Cache):
        _CACHE = {}
    
        def get(self, url):
            return MemoryCache._CACHE.get(url)
    
        def set(self, url, content):
            MemoryCache._CACHE[url] = content
    

    Usage:

    http = ...
    service = discovery.build('calendar', 'v3', http=http, cache=MemoryCache())
    

    googleapiclient.discovery_cache.base.Cache

  20. viktoratedgetier commented on Jun 18, 2026

    @viktoratedgetier

    In case anyone uses the workaround from #325 (comment), beware of the memory leak it can cause in long-running processes. Better to put a bound onto it.

    from cachetools import LRUCache
    from googleapiclient.discovery_cache.base import Cache as DiscoveryCache
    
    # Set a cache boundary to prevent a memory leak
    _discovery_cache: LRUCache = LRUCache(maxsize=100)
    
    
    class MemoryCache(DiscoveryCache):
        def get(self, url: str) -> Optional[str]:
            return _discovery_cache.get(url)
    
        def set(self, url: str, content: str) -> None:
            _discovery_cache[url] = content
    

    Usage:

    from google.oauth2.credentials import Credentials
    from googleapiclient.discovery import build
    
    refresh_token = ...
    credentials = Credentials.from_authorized_user_info(
          {
              "refresh_token": refresh_token,
              "client_id": GOOGLE_APP_CLIENT_ID,
              "client_secret": GOOGLE_APP_CLIENT_SECRET,
          }
      )
    gmail_service = build("gmail", "v1", credentials=credentials, cache=MemoryCache())
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

type: feature request

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions