def upload_file(self, file_name, file_path, parent_id=None): file_metadata = {'name': file_name} if parent_id: file_metadata['parents'] = [parent_id] media = MediaFileUpload(file_path, resumable=True) file = self.files().create(body=file_metadata, media_body=media, fields='id') media.stream() response = None while response is None: try: status, response = file.next_chunk() if status: print("Uploaded %d%% of %s." % (int(status.progress() * 100), file_name)) except Exception as e: print("Error uploading file %s: %s" % (file_name, e)) print("status info:", status) print("Upload of %s Complete!" % file_name) return response
def upload_file(self, file_id, file_name, file_path, file_gid=None, parent_gid=None, progress_queue=Queue()): print("uploading file at:", file_path) self.cancel_uploads[file_id] = False file_metadata = {'name': file_name} if parent_gid and not file_gid: file_metadata['parents'] = [parent_gid] max_retries = 5 while max_retries != 0: try: os.rename(file_path, file_path) break except Exception as e: # File was probably in use so create a new upload request print("file still in use, waiting...", e) time.sleep(.5) max_retries -= 1 file = None media = MediaFileUpload(file_path, resumable=True) if file_gid: file = self.files().update( fileId=file_gid, body=file_metadata, media_body=media, fields='id' ) else: file = self.files().create( body=file_metadata, media_body=media, fields='id') media.stream() progress = 0 response = None progress_queue.put({"progress": 0, "in_failure": False}) fail_count = 0 while response is None and not self.is_canceled(file_id) and fail_count < 10: try: status, response = file.next_chunk() if status: progress = status.progress() print("Uploaded %d%% of %s." % (int(progress * 100), file_name)) progress_queue.put({"progress": progress, "in_failure": False}) except Exception as e: print("Error uploading file %s: %s" % (file_name, e)) progress_queue.put({"progress": progress, "in_failure": True}) time.sleep(.5) if type(e) is HttpError: media = MediaFileUpload(file_path, resumable=True) file = self.files().create( body=file_metadata, media_body=media, fields='id') media.stream() progress_queue.put({"progress": 0, "in_failure": True}) fail_count += 1 progress_queue.put(False) return response