Python apiclient.http.MediaFileUpload() Examples

The following are 9 code examples of apiclient.http.MediaFileUpload(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module apiclient.http , or try the search function .
Example #1
Source File: gdrive_upload.py    From Gdrivedownloader with MIT License 7 votes vote down vote up
def upload_file(file_path, file_name, mime_type):
# Create Google Drive service instance
    drive_service = build('drive', 'v2', http=http)
# File body description
    media_body = MediaFileUpload(file_path,
                                 mimetype=mime_type,
                                 resumable=True)
    body = {
        'title': file_name,
        'description': 'backup',
        'mimeType': mime_type,
    }
# Permissions body description: anyone who has link can upload
# Other permissions can be found at https://developers.google.com/drive/v2/reference/permissions
    permissions = {
        'role': 'reader',
        'type': 'anyone',
        'value': None,
        'withLink': True
    }
# Insert a file
    file = drive_service.files().insert(body=body, media_body=media_body).execute()
# Insert new permissions
    drive_service.permissions().insert(fileId=file['id'], body=permissions).execute()
# Define file instance and get url for download
    file = drive_service.files().get(fileId=file['id']).execute()
    download_url = file.get('webContentLink')
    return download_url 
Example #2
Source File: youtube.py    From Zoom2Youtube with MIT License 6 votes vote down vote up
def upload_video(self, options: dict):
        """
        Options is Dict with

        file - filepath to video
        title - title of video
        privacyStatus

        :param options:
        :return:
        """
        body = self._generate_meta_data(options)
        connector = self.client.get_authenticated_service()
        insert_request = connector \
            .videos() \
            .insert(part=",".join(body.keys()),
                    body=body,
                    media_body=MediaFileUpload(options.get('file'),
                                               chunksize=-1,
                                               resumable=True))
        try:
            return self._real_upload_video(insert_request)
        except Exception as e:
            print(str(e)) 
Example #3
Source File: google_drive.py    From Packt-Publishing-Free-Learning with MIT License 6 votes vote down vote up
def __insert_file_into_folder(self, file_name, path, parent_folder_id, file_mime_type=None):
        parent_id = parent_folder_id if parent_folder_id is None else [parent_folder_id]
        file_metadata = {
          'name': file_name,
          'parents': parent_id
        }
        media = MediaFileUpload(
            path,
            mimetype=file_mime_type,  # if None, it will be guessed
            resumable=True
        )
        file = self._service.files().create(body=file_metadata, media_body=media, fields='id').execute()
        logger.debug('File ID: {}'.format(file.get('id')))
        return file.get('id') 
Example #4
Source File: archive_deployment_packages.py    From Lecture-Series-Python with MIT License 6 votes vote down vote up
def upload_file_to_drive(service, file_name, path_to_file):
    file_metadata = {
        'name': file_name,
        'parents': ['0B_qHZ9yaJLRnd1RSUTNZazdicGs']
    }
    media = MediaFileUpload(f'{path_to_file}\\{file_name}', resumable=True)
    request = service.files().create(body=file_metadata,
                                     media_body=media,
                                     fields='id')
    response = None

    while response is None:
        status, response = request.next_chunk()
        if status:
            sys.stdout.write(("Uploaded %d%%. \r" % int(status.progress() * 100)))
            sys.stdout.flush() 
Example #5
Source File: GoSyncModel.py    From gosync with GNU General Public License v2.0 5 votes vote down vote up
def CreateRegularFile(self, file_path, parent='root', uploaded=False):
        self.SendlToLog(3,"Create file %s\n" % file_path)
        filename = self.PathLeaf(file_path)
        file_metadata = {'name': filename}
        file_metadata['parents'] = [parent]
        media = MediaFileUpload(file_path, resumable=True)
        upfile = self.drive.files().create(body=file_metadata,
                                    media_body=media,
                                    fields='id').execute() 
Example #6
Source File: upload.py    From foos with GNU General Public License v3.0 5 votes vote down vote up
def initialize_upload(title=None, file='/tmp/replay/replay_long.mp4'):
    youtube = get_authenticated_service()
    if not title:
        title = 'Tuenti foos replay'
    body = {
        'snippet': {
            'title': title,
            'description': title,
        }
    }

    # Call the API's videos.insert method to create and upload the video.
    insert_request = youtube.videos().insert(
        part=",".join(list(body.keys())),
        body=body,
        # The chunksize parameter specifies the size of each chunk of data, in
        # bytes, that will be uploaded at a time. Set a higher value for
        # reliable connections as fewer chunks lead to faster uploads. Set a lower
        # value for better recovery on less reliable connections.
        media_body=MediaFileUpload(file, chunksize=-1, resumable=True))

    return resumable_upload(insert_request)


# This method implements an exponential backoff strategy to resume a
# failed upload. 
Example #7
Source File: __init__.py    From ezsheets with GNU General Public License v3.0 5 votes vote down vote up
def upload(filename):
    if not IS_INITIALIZED:
        init()
    # TODO - be able to pass a file object for `filename`, not just a string name of a file on the hard drive.

    if filename.lower().endswith(".xlsx"):
        mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    elif filename.lower().endswith(".ods"):
        mimeType = "application/x-vnd.oasis.opendocument.spreadsheet"
    elif filename.lower().endswith(".csv"):
        mimeType = "text/csv"
    elif filename.lower().endswith(".tsv"):
        mimeType = "text/tab-separated-values"
    else:
        raise ValueError(
            "File to upload must be a .xlsx (Excel), .ods (OpenOffice), .csv (Comma-separated), or .tsv (Tab-separated) file type."
        )

    if not os.path.exists(filename):
        raise FileNotFoundError("Unable to find a file named %s" % (os.path.abspath(filename)))

    media = MediaFileUpload(filename, mimetype=mimeType)
    # file = DRIVE_SERVICE.files().create(body={'name': filename, 'mimeType': 'application/vnd.google-apps.spreadsheet'},
    #                                    media_body=media,
    #                                    fields='id').execute()
    file = _makeRequest(
        "drive.create",
        **{
            "body": {"name": filename, "mimeType": "application/vnd.google-apps.spreadsheet"},
            "media_body": media,
            "fields": "id",
        }
    )
    return Spreadsheet(file.get("id")) 
Example #8
Source File: build_export_dag.py    From ethereum-etl-airflow with MIT License 5 votes vote down vote up
def upload_to_gcs(gcs_hook, bucket, object, filename, mime_type='application/octet-stream'):
    from apiclient.http import MediaFileUpload
    from googleapiclient import errors

    service = gcs_hook.get_conn()

    if os.path.getsize(filename) > 10 * MEGABYTE:
        media = MediaFileUpload(filename, mime_type, resumable=True)

        try:
            request = service.objects().insert(bucket=bucket, name=object, media_body=media)
            response = None
            while response is None:
                status, response = request.next_chunk()
                if status:
                    logging.info("Uploaded %d%%." % int(status.progress() * 100))

            return True
        except errors.HttpError as ex:
            if ex.resp['status'] == '404':
                return False
            raise
    else:
        media = MediaFileUpload(filename, mime_type)

        try:
            service.objects().insert(bucket=bucket, name=object, media_body=media).execute()
            return True
        except errors.HttpError as ex:
            if ex.resp['status'] == '404':
                return False
            raise


# Can download big files unlike gcs_hook.download which saves files in memory first 
Example #9
Source File: gDrive.py    From X-tra-Telegram with Apache License 2.0 4 votes vote down vote up
def upload_file(http, file_path, file_name, mime_type, event, parent_id):
    # Create Google Drive service instance
    drive_service = build("drive", "v2", http=http, cache_discovery=False)
    # File body description
    media_body = MediaFileUpload(file_path, mimetype=mime_type, resumable=True)
    body = {
        "title": file_name,
        "description": "Uploaded using Userbot gDrive v1",
        "mimeType": mime_type,
    }
    if parent_id is not None:
        body["parents"] = [{"id": parent_id}]
    # Permissions body description: anyone who has link can upload
    # Other permissions can be found at https://developers.google.com/drive/v2/reference/permissions
    permissions = {
        "role": "reader",
        "type": "anyone",
        "value": None,
        "withLink": True
    }
    # Insert a file
    file = drive_service.files().insert(body=body, media_body=media_body)
    response = None
    display_message = ""
    while response is None:
        status, response = file.next_chunk()  #Credits: https://github.com/AvinashReddy3108/PaperplaneExtended/commit/df65da55d16a6563aa9023cac2bedf43248379f5
        await asyncio.sleep(1)
        if status:
            percentage = int(status.progress() * 100)
            progress_str = "[{0}{1}]\nProgress: {2}%\n".format(
                "".join(["█" for i in range(math.floor(percentage / 5))]),
                "".join(["░" for i in range(20 - math.floor(percentage / 5))]),
                round(percentage, 2)
            )
            current_message = f"Uploading to G-Drive:\nFile Name: `{file_name}`\n{progress_str}"
            if display_message != current_message:
                try:
                    await event.edit(current_message)
                    display_message = current_message
                except Exception as e:
                    logger.info(str(e))
                    pass
    file_id = response.get("id")
    # Insert new permissions
    drive_service.permissions().insert(fileId=file_id, body=permissions).execute()
    # Define file instance and get url for download
    file = drive_service.files().get(fileId=file_id).execute()
    download_url = file.get("webContentLink")
    return download_url