gnosticdev commited on
Commit
f919264
·
verified ·
1 Parent(s): 215af76

Create google_drive_upload.py

Browse files
Files changed (1) hide show
  1. google_drive_upload.py +33 -0
google_drive_upload.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from google.oauth2.credentials import Credentials
3
+ from google_auth_oauthlib.flow import InstalledAppFlow
4
+ from google.auth.transport.requests import Request
5
+ from googleapiclient.discovery import build
6
+ from googleapiclient.http import MediaFileUpload
7
+
8
+ # Si modificas estos SCOPES, borra el archivo token.json.
9
+ SCOPES = ['https://www.googleapis.com/auth/drive.file']
10
+
11
+ def authenticate_google_drive():
12
+ creds = None
13
+ if os.path.exists('token.json'):
14
+ creds = Credentials.from_authorized_user_file('token.json', SCOPES)
15
+ if not creds or not creds.valid:
16
+ if creds and creds.expired and creds.refresh_token:
17
+ creds.refresh(Request())
18
+ else:
19
+ flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
20
+ creds = flow.run_local_server(port=0)
21
+ with open('token.json', 'w') as token:
22
+ token.write(creds.to_json())
23
+ return creds
24
+
25
+ def upload_to_google_drive(file_path):
26
+ creds = authenticate_google_drive()
27
+ service = build('drive', 'v3', credentials=creds)
28
+
29
+ file_metadata = {'name': os.path.basename(file_path)}
30
+ media = MediaFileUpload(file_path, resumable=True)
31
+ file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
32
+ print(f"Archivo subido con ID: {file.get('id')}")
33
+ return file.get('id')