Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add drive download utility functions and test #462

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions services/google_drive_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from io import BytesIO
import json
import os
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
from googleapiclient.errors import HttpError
from google.oauth2.service_account import Credentials

SERVICE_ACCOUNT_FILE = os.environ['GOOGLE_SERVICE_ACCOUNT_FILE']

from logger import create_log

logger = create_log(__name__)

service_account_info=json.loads(SERVICE_ACCOUNT_FILE)
scopes = ['https://www.googleapis.com/auth/drive']
credentials = Credentials.from_service_account_info(service_account_info, scopes=scopes)

drive_service = build('drive', 'v3', credentials=credentials)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I left this as functions (instead of encapsulating it in a class) based on your comments -- this breaks from the other files in /services but I can see an argument for doing it either way. Let me know if this is what you were envisioning.


def get_drive_file(file_id: str) -> BytesIO:
request = drive_service.files().get_media(fileId=file_id)
file = BytesIO()

try:
downloader = MediaIoBaseDownload(file, request)

done = False
while not done:
status, done = downloader.next_chunk()

except HttpError as error:
logger.warning(f"HTTP error occurred when downloading Drive file {file_id}: {error}")
return None
except Exception as err:
logger.exception(f"Error occurred when downloading Drive file {file_id}: {error}")

return file
14 changes: 14 additions & 0 deletions tests/integration/test_google_integration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import os
from load_env import load_env_file

load_env_file('local-compose', file_string='config/local-compose.yaml')

from services.google_drive_service import get_drive_file

TEST_ID = '1GBskazIv6j2BjOolNYqJKKIJC8iYhTcs'

def test_get_drive_file():
file = get_drive_file(TEST_ID)

assert file != None
assert file.seek(0, 2) > 1
Loading