Glider
Loading...
Searching...
No Matches
GenerateToken.py
Go to the documentation of this file.
1from __future__ import print_function
2
3import os.path
4
5from google.auth.transport.requests import Request
6from google.oauth2.credentials import Credentials
7from google_auth_oauthlib.flow import InstalledAppFlow
8from googleapiclient.discovery import build
9from googleapiclient.errors import HttpError
10
11# If modifying these scopes, delete the file token.json.
12
13SCOPES = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive.readonly", "https://www.googleapis.com/auth/drive.metadata.readonly", "https://www.googleapis.com/auth/drive.appdata", "https://www.googleapis.com/auth/drive.metadata", "https://www.googleapis.com/auth/drive.photos.readonly"]
14
15def main():
16 """Shows basic usage of the Drive v3 API.
17 Prints the names and ids of the first 10 files the user has access to.
18 """
19 creds = None
20 # The file token.json stores the user's access and refresh tokens, and is
21 # created automatically when the authorization flow completes for the first
22 # time.
23 if os.path.exists('token.json'):
24 creds = Credentials.from_authorized_user_file('token.json', SCOPES)
25 # If there are no (valid) credentials available, let the user log in.
26 if not creds or not creds.valid:
27 if creds and creds.expired and creds.refresh_token:
28 creds.refresh(Request())
29 else:
30 flow = InstalledAppFlow.from_client_secrets_file(
31 'client_secret.json', SCOPES)
32 creds = flow.run_local_server(port=0)
33 # Save the credentials for the next run
34 with open('token.json', 'w') as token:
35 token.write(creds.to_json())
36
37 try:
38 service = build('drive', 'v3', credentials=creds)
39
40 # Call the Drive v3 API
41 results = service.files().list(
42 pageSize=10, fields="nextPageToken, files(id, name)").execute()
43 items = results.get('files', [])
44
45 if not items:
46 print('No files found.')
47 return
48 print('Files:')
49 for item in items:
50 print(u'{0} ({1})'.format(item['name'], item['id']))
51 except HttpError as error:
52 # TODO(developer) - Handle errors from drive API.
53 print(f'An error occurred: {error}')
54
55
56if __name__ == '__main__':
57 main()