Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created March 17, 2023 13:30
Show Gist options
  • Save Fhernd/7d3487b0f37967e7f223b629e5afe105 to your computer and use it in GitHub Desktop.
Save Fhernd/7d3487b0f37967e7f223b629e5afe105 to your computer and use it in GitHub Desktop.
Accedo a Google Drive desde Python
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from google.oauth2 import service_account
def get_service(api_name, api_version, scopes, key_file_location):
"""Get a service that communicates to a Google API.
Args:
api_name: The name of the api to connect to.
api_version: The api version to connect to.
scopes: A list auth scopes to authorize for the application.
key_file_location: The path to a valid service account JSON key file.
Returns:
A service that is connected to the specified API.
"""
credentials = service_account.Credentials.from_service_account_file(key_file_location)
scoped_credentials = credentials.with_scopes(scopes)
# Build the service object.
service = build(api_name, api_version, credentials=scoped_credentials)
return service
def main():
"""Shows basic usage of the Drive v3 API.
Prints the names and ids of the first 10 files the user has access to.
"""
# Define the auth scopes to request.
scope = 'https://www.googleapis.com/auth/drive.metadata.readonly'
key_file_location = 'credentials.json'
try:
# Authenticate and construct service.
service = get_service(
api_name='drive',
api_version='v3',
scopes=[scope],
key_file_location=key_file_location)
# Call the Drive v3 API
results = service.files().list(
pageSize=10, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
return
print('Files:')
for item in items:
print(u'{0} ({1})'.format(item['name'], item['id']))
except HttpError as error:
# TODO(developer) - Handle errors from drive API.
print(f'An error occurred: {error}')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment