Add method to only create file if it doesn't exist

This commit is contained in:
Joey Payne 2016-05-24 10:37:32 -06:00
commit e90b545391
2 changed files with 48 additions and 6 deletions

View file

@ -66,9 +66,9 @@ class GoogleDrive(object):
if parent_id:
params['body'] = {'parents': [parent_id]}
google_file = GoogleFile.create(self.service, folder_name,
mime_type=MimeTypes.Folder,
**params)
google_file = GoogleFile.get_or_create(self.service, folder_name,
mime_type=MimeTypes.Folder,
**params)
parent_id = google_file.meta_data['id']
parent_folders.append(google_file)
@ -78,9 +78,10 @@ class GoogleDrive(object):
if parent_id:
main_params['body'] = {'parents': [parent_id]}
main_file = GoogleFile.create(self.service, file_name,
mime_type=mime_type,
**main_params)
main_file = GoogleFile.get_or_create(self.service, file_name,
mime_type=mime_type,
content=content,
**main_params)
result = parent_folders + [main_file]

View file

@ -63,6 +63,47 @@ class GoogleFile(object):
return google_file
@staticmethod
def get_or_create(service, name, mime_type=None, content=None, body=None, **params):
"""Gets a file in GoogleDrive or creates it if it doesn't exist
Args:
service: the API service object
name: the name of the file, including the extension
mime_type: the mimetype of the file. See config.MimeTypes
content: the content string of the file
body: a dict-like object, describes additional request body args
params: any additional parameters to send to the API
Returns:
A GoogleFile object
"""
list_fields = config.ALL_FILE_FIELDS
body = body or {}
body.update({'name': name})
query = 'name = "{}"'.format(name)
parents = body.get('parents', [])
if parents:
parent_id = parents[0]
query = 'name = "{}" and "{}" in parents'.format(name, parent_id)
files = self.service.files().list(fields=list_fields, q=query).execute().get('files')
if files:
meta_data = files[0]
google_file = GoogleFile(service, meta_data)
return google_file
else:
return GoogleFile.create(service, name,
mimetype=mime_type,
content=content,
body=body, **params)
def refresh(self):
"""Gets the meta data of the file from Google Drive