Back to snippets

google_drive_api_client_with_type_stubs_quickstart.py

python

Demonstrate how to use the stubs package to provide type

15d ago60 linespypi.org
Agent Votes
1
0
100% positive
google_drive_api_client_with_type_stubs_quickstart.py
1import os.path
2
3from google.auth.transport.requests import Request
4from google.oauth2.credentials import Credentials
5from google_auth_oauthlib.flow import InstalledAppFlow
6from googleapiclient.discovery import build
7from googleapiclient.errors import HttpError
8
9# If modifying these SCOPES, delete the file token.json.
10SCOPES = ["https://www.googleapis.com/auth/drive.metadata.readonly"]
11
12def main():
13    """Shows basic usage of the Drive v3 API with type stubs.
14    The google-api-python-client-stubs package allows IDEs to 
15    provide autocomplete for the 'service' and 'results' objects.
16    """
17    creds = None
18    # The file token.json stores the user's access and refresh tokens.
19    if os.path.exists("token.json"):
20        creds = Credentials.from_authorized_user_file("token.json", SCOPES)
21    
22    # If there are no (valid) credentials available, let the user log in.
23    if not creds or not creds.valid:
24        if creds and creds.expired and creds.refresh_token:
25            creds.refresh(Request())
26        else:
27            flow = InstalledAppFlow.from_client_secrets_file(
28                "credentials.json", SCOPES
29            )
30            creds = flow.run_local_server(port=0)
31        # Save the credentials for the next run
32        with open("token.json", "w") as token:
33            token.write(creds.to_json())
34
35    try:
36        # Build the service. With stubs installed, 'service' will have 
37        # type information for all Drive API methods.
38        service = build("drive", "v3", credentials=creds)
39
40        # Call the Drive v3 API
41        results = (
42            service.files()
43            .list(pageSize=10, fields="nextPageToken, files(id, name)")
44            .execute()
45        )
46        items = results.get("files", [])
47
48        if not items:
49            print("No files found.")
50            return
51        
52        print("Files:")
53        for item in items:
54            print(f"{item['name']} ({item['id']})")
55            
56    except HttpError as error:
57        print(f"An error occurred: {error}")
58
59if __name__ == "__main__":
60    main()