gnosticdev commited on
Commit
b529f3c
verified
1 Parent(s): bffa19c

Update google_drive_upload.py

Browse files
Files changed (1) hide show
  1. google_drive_upload.py +22 -21
google_drive_upload.py CHANGED
@@ -1,7 +1,6 @@
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
 
@@ -9,25 +8,27 @@ from googleapiclient.http import MediaFileUpload
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')
 
 
 
 
1
  import os
2
+ import json
3
+ from google.oauth2.service_account import Credentials
 
4
  from googleapiclient.discovery import build
5
  from googleapiclient.http import MediaFileUpload
6
 
 
8
  SCOPES = ['https://www.googleapis.com/auth/drive.file']
9
 
10
  def authenticate_google_drive():
11
+ """Autentica usando una cuenta de servicio."""
12
+ # Cargar las credenciales desde el secreto
13
+ service_account_info = json.loads(os.getenv('GOOGLE_SERVICE_ACCOUNT', '{}'))
14
+ if not service_account_info:
15
+ raise ValueError("No se encontr贸 la informaci贸n de la cuenta de servicio.")
16
+
17
+ # Crear credenciales
18
+ creds = Credentials.from_service_account_info(service_account_info, scopes=SCOPES)
 
 
 
19
  return creds
20
 
21
  def upload_to_google_drive(file_path):
22
+ """Sube un archivo a Google Drive."""
23
+ try:
24
+ creds = authenticate_google_drive()
25
+ service = build('drive', 'v3', credentials=creds)
26
 
27
+ file_metadata = {'name': os.path.basename(file_path)}
28
+ media = MediaFileUpload(file_path, resumable=True)
29
+ file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
30
+ print(f"Archivo subido con ID: {file.get('id')}")
31
+ return file.get('id')
32
+ except Exception as e:
33
+ print(f"Error subiendo a Google Drive: {e}")
34
+ return None