Update google_drive_upload.py
Browse files- google_drive_upload.py +22 -21
google_drive_upload.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
import os
|
| 2 |
-
|
| 3 |
-
from
|
| 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 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
if not
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 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 |
-
|
| 27 |
-
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|