1# Copyright 2014 Google Inc. All Rights Reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15"""Caching utility for the discovery document.""" 16 17from __future__ import absolute_import 18 19import logging 20import datetime 21import os 22 23LOGGER = logging.getLogger(__name__) 24 25DISCOVERY_DOC_MAX_AGE = 60 * 60 * 24 # 1 day 26DISCOVERY_DOC_DIR = os.path.join(os.path.dirname( 27 os.path.realpath(__file__)), 'documents') 28 29def autodetect(): 30 """Detects an appropriate cache module and returns it. 31 32 Returns: 33 googleapiclient.discovery_cache.base.Cache, a cache object which 34 is auto detected, or None if no cache object is available. 35 """ 36 if 'APPENGINE_RUNTIME' in os.environ: 37 try: 38 from google.appengine.api import memcache 39 from . import appengine_memcache 40 41 return appengine_memcache.cache 42 except Exception: 43 pass 44 try: 45 from . import file_cache 46 47 return file_cache.cache 48 except Exception: 49 LOGGER.info("file_cache is only supported with oauth2client<4.0.0", 50 exc_info=False) 51 return None 52 53def get_static_doc(serviceName, version): 54 """Retrieves the discovery document from the directory defined in 55 DISCOVERY_DOC_DIR corresponding to the serviceName and version provided. 56 57 Args: 58 serviceName: string, name of the service. 59 version: string, the version of the service. 60 61 Returns: 62 A string containing the contents of the JSON discovery document, 63 otherwise None if the JSON discovery document was not found. 64 """ 65 66 content = None 67 doc_name = "{}.{}.json".format(serviceName, version) 68 69 try: 70 with open(os.path.join(DISCOVERY_DOC_DIR, doc_name), 'r') as f: 71 content = f.read() 72 except FileNotFoundError: 73 # File does not exist. Nothing to do here. 74 pass 75 76 return content 77 78