Spaces:
Sleeping
Sleeping
| # File: backend/drive_test.py | |
| import os.path | |
| from google.auth.transport.requests import Request | |
| from google.oauth2.credentials import Credentials | |
| from google_auth_oauthlib.flow import InstalledAppFlow | |
| from googleapiclient.discovery import build | |
| # If modifying these scopes, delete the file token.json. | |
| # We ONLY ask for read-only access to metadata (Project constraint: No content storage) | |
| SCOPES = ["https://www.googleapis.com/auth/drive.metadata.readonly"] | |
| def connect_to_drive(): | |
| """Shows basic usage of the Drive v3 API.""" | |
| creds = None | |
| # The file token.json stores the user's access and refresh tokens, and is | |
| # created automatically when the authorization flow completes for the first time. | |
| if os.path.exists("backend/token.json"): | |
| creds = Credentials.from_authorized_user_file("backend/token.json", SCOPES) | |
| # If there are no (valid) credentials available, let the user log in. | |
| if not creds or not creds.valid: | |
| if creds and creds.expired and creds.refresh_token: | |
| print("Refreshing Expired Token...") | |
| creds.refresh(Request()) | |
| else: | |
| print("Initiating New Login...") | |
| # We look for credentials.json in the backend folder | |
| flow = InstalledAppFlow.from_client_secrets_file( | |
| "backend/credentials.json", SCOPES | |
| ) | |
| # This opens a local browser for you to sign in | |
| creds = flow.run_local_server(port=0) | |
| # Save the credentials for the next run | |
| with open("backend/token.json", "w") as token: | |
| token.write(creds.to_json()) | |
| try: | |
| service = build("drive", "v3", credentials=creds) | |
| # Call the Drive v3 API | |
| print("\nSuccessfully connected! Fetching top 10 files...\n") | |
| # We only ask for specific fields: id, name, mimeType (file type) | |
| results = ( | |
| service.files() | |
| .list(pageSize=10, fields="nextPageToken, files(id, name, mimeType)") | |
| .execute() | |
| ) | |
| items = results.get("files", []) | |
| if not items: | |
| print("No files found.") | |
| return | |
| print(f"{'FILE NAME':<40} | {'TYPE'}") | |
| print("-" * 60) | |
| for item in items: | |
| # Simple truncation for display | |
| name = (item["name"][:35] + '..') if len(item["name"]) > 35 else item["name"] | |
| print(f"{name:<40} | {item['mimeType']}") | |
| except Exception as error: | |
| print(f"An error occurred: {error}") | |
| if __name__ == "__main__": | |
| # Ensure we are running from the root folder context roughly | |
| if not os.path.exists("backend/credentials.json"): | |
| print("ERROR: backend/credentials.json not found!") | |
| print("Please make sure you are running this from the DocuSort root folder.") | |
| else: | |
| connect_to_drive() |