Spaces:
Building
Building
File size: 1,364 Bytes
f919264 b529f3c f919264 b529f3c f919264 7c121aa b529f3c f919264 b529f3c 7c121aa ea6b145 7c121aa b529f3c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import os
import json
from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
# Si modificas estos SCOPES, borra el archivo token.json.
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 |