|
import os |
|
import json |
|
from google.oauth2.service_account import Credentials |
|
from googleapiclient.discovery import build |
|
from googleapiclient.http import MediaFileUpload |
|
|
|
|
|
SCOPES = ['https://www.googleapis.com/auth/drive.file'] |
|
|
|
def authenticate_google_drive(): |
|
"""Autentica usando una cuenta de servicio.""" |
|
service_account_info = json.loads(os.getenv('GOOGLE_SERVICE_ACCOUNT', '{}')) |
|
if not service_account_info: |
|
raise ValueError("No se encontr贸 la informaci贸n de la cuenta de servicio.") |
|
creds = Credentials.from_service_account_info(service_account_info, scopes=SCOPES) |
|
return creds |
|
|
|
def upload_to_google_drive(file_path, folder_id=None): |
|
"""Sube un archivo a Google Drive.""" |
|
try: |
|
creds = authenticate_google_drive() |
|
service = build('drive', 'v3', credentials=creds) |
|
|
|
file_metadata = {'name': os.path.basename(file_path)} |
|
if folder_id: |
|
file_metadata['parents'] = [folder_id] |
|
|
|
media = MediaFileUpload(file_path, resumable=True) |
|
file = service.files().create(body=file_metadata, media_body=media, fields='id').execute() |
|
print(f"Archivo subido con ID: {file.get('id')}") |
|
return file.get('id') |
|
except Exception as e: |
|
print(f"Error subiendo a Google Drive: {e}") |
|
return None |