当前位置: 首页>>代码示例>>Python>>正文


Python http.MediaFileUpload方法代码示例

本文整理汇总了Python中apiclient.http.MediaFileUpload方法的典型用法代码示例。如果您正苦于以下问题:Python http.MediaFileUpload方法的具体用法?Python http.MediaFileUpload怎么用?Python http.MediaFileUpload使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在apiclient.http的用法示例。


在下文中一共展示了http.MediaFileUpload方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: upload_video

# 需要导入模块: from apiclient import http [as 别名]
# 或者: from apiclient.http import MediaFileUpload [as 别名]
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)) 
开发者ID:Welltory,项目名称:Zoom2Youtube,代码行数:26,代码来源:youtube.py

示例2: upload_file

# 需要导入模块: from apiclient import http [as 别名]
# 或者: from apiclient.http import MediaFileUpload [as 别名]
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 
开发者ID:cyberboysumanjay,项目名称:Gdrivedownloader,代码行数:30,代码来源:gdrive_upload.py

示例3: upload_file_to_drive

# 需要导入模块: from apiclient import http [as 别名]
# 或者: from apiclient.http import MediaFileUpload [as 别名]
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() 
开发者ID:Github-Classroom-Cybros,项目名称:Lecture-Series-Python,代码行数:18,代码来源:archive_deployment_packages.py

示例4: CreateRegularFile

# 需要导入模块: from apiclient import http [as 别名]
# 或者: from apiclient.http import MediaFileUpload [as 别名]
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() 
开发者ID:hschauhan,项目名称:gosync,代码行数:11,代码来源:GoSyncModel.py

示例5: __insert_file_into_folder

# 需要导入模块: from apiclient import http [as 别名]
# 或者: from apiclient.http import MediaFileUpload [as 别名]
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') 
开发者ID:luk6xff,项目名称:Packt-Publishing-Free-Learning,代码行数:16,代码来源:google_drive.py

示例6: initialize_upload

# 需要导入模块: from apiclient import http [as 别名]
# 或者: from apiclient.http import MediaFileUpload [as 别名]
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. 
开发者ID:swehner,项目名称:foos,代码行数:28,代码来源:upload.py

示例7: upload

# 需要导入模块: from apiclient import http [as 别名]
# 或者: from apiclient.http import MediaFileUpload [as 别名]
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")) 
开发者ID:asweigart,项目名称:ezsheets,代码行数:36,代码来源:__init__.py

示例8: upload_to_gcs

# 需要导入模块: from apiclient import http [as 别名]
# 或者: from apiclient.http import MediaFileUpload [as 别名]
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 
开发者ID:blockchain-etl,项目名称:ethereum-etl-airflow,代码行数:37,代码来源:build_export_dag.py

示例9: upload_file

# 需要导入模块: from apiclient import http [as 别名]
# 或者: from apiclient.http import MediaFileUpload [as 别名]
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 
开发者ID:Dark-Princ3,项目名称:X-tra-Telegram,代码行数:51,代码来源:gDrive.py


注:本文中的apiclient.http.MediaFileUpload方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。