def ia_credentials_helper(client_id, client_secret, 
                          credentials_cache_file="credentials.json",
                          cache_key="default"):
    def _load_credentials(key):
        with open(credentials_cache_file, 'rb') as inf:
            cache = json.load(inf)
        cred_json = cache[key]
        return OAuth2Credentials.from_json(cred_json)

    def _save_credentials(key, credentials):
        cache = {}
        try:
            with open(credentials_cache_file, 'rb') as inf:
                cache = json.load(inf)
        except (IOError, ValueError), e:
            pass
        cache[key] = credentials.to_json()
        with open(credentials_cache_file, 'wb') as ouf:
            json.dump(cache, ouf)

    credentials_key = "%s/%s/%s" % (client_id, client_secret, cache_key)
    try:
        credentials = _load_credentials(credentials_key)
        if credentials.access_token_expired:
            http = httplib2.Http()
            credentials.refresh(http)
    except (IOError, 
            ValueError, 
            KeyError, 
            AccessTokenRefreshError), e:
        # Check https://developers.google.com/drive/scopes for all available scopes
        OAUTH_SCOPE = ('https://www.googleapis.com/auth/drive '+
                       'https://spreadsheets.google.com/feeds')
        # Redirect URI for installed apps
        REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

        # Run through the OAuth flow and retrieve credentials
        flow = OAuth2WebServerFlow(client_id, client_secret, OAUTH_SCOPE,
                                   redirect_uri=REDIRECT_URI)
        authorize_url = flow.step1_get_authorize_url()
        print('Go to the following link in your browser:\n' + authorize_url)
        code = raw_input('Enter verification code: ').strip()
        credentials = flow.step2_exchange(code)

    _save_credentials(credentials_key, credentials)
    return credentials
Helper function to manage a credentials cache during testing.
dataset/ETHPy150Open mbrenig/SheetSync/sheetsync/__init__.py/ia_credentials_helper