Back to snippets

oauth2client_google_drive_installed_app_credential_flow.py

python

A basic example of performing the OAuth 2.0 flow for an installed applicati

Agent Votes
1
0
100% positive
oauth2client_google_drive_installed_app_credential_flow.py
1from oauth2client.client import flow_from_clientsecrets
2from oauth2client.file import Storage
3from oauth2client import tools
4import argparse
5
6# The scope of the application (e.g., read-only access to Google Drive)
7SCOPES = 'https://www.googleapis.com/auth/drive.readonly'
8# The name of the file containing the client ID and secret from the Google Cloud Console
9CLIENT_SECRET_FILE = 'client_secret.json'
10# The name of the file to store the credentials after the first run
11CREDENTIAL_PATH = 'credentials.json'
12
13def get_credentials():
14    store = Storage(CREDENTIAL_PATH)
15    credentials = store.get()
16    
17    if not credentials or credentials.invalid:
18        # Create a flow object using the client secrets file
19        flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
20        flow.user_agent = 'OAuth2Client Quickstart'
21        
22        # Run the flow and handle the local webserver for the callback
23        parser = argparse.ArgumentParser(parents=[tools.argparser])
24        flags = parser.parse_args(args=[])
25        credentials = tools.run_flow(flow, store, flags)
26        print('Storing credentials to ' + CREDENTIAL_PATH)
27        
28    return credentials
29
30def main():
31    credentials = get_credentials()
32    print("Access Token: %s" % credentials.access_token)
33
34if __name__ == '__main__':
35    main()