本文整理汇总了Python中googleapiclient.http.MediaFileUpload方法的典型用法代码示例。如果您正苦于以下问题:Python http.MediaFileUpload方法的具体用法?Python http.MediaFileUpload怎么用?Python http.MediaFileUpload使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类googleapiclient.http
的用法示例。
在下文中一共展示了http.MediaFileUpload方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: file_handler
# 需要导入模块: from googleapiclient import http [as 别名]
# 或者: from googleapiclient.http import MediaFileUpload [as 别名]
def file_handler(update, context):
"""handles the uploaded files"""
file = context.bot.getFile(update.message.document.file_id)
file.download(update.message.document.file_name)
doc = update.message.document
service = build('drive', 'v3', credentials=getCreds(),cache_discovery=False)
filename = doc.file_name
metadata = {'name': filename}
media = MediaFileUpload(filename, chunksize=1024 * 1024, mimetype=doc.mime_type, resumable=True)
request = service.files().create(body=metadata,
media_body=media)
response = None
while response is None:
status, response = request.next_chunk()
if status:
print( "Uploaded %d%%." % int(status.progress() * 100))
context.bot.send_message(chat_id=update.effective_chat.id, text="✅ File uploaded!")
示例2: initialize_upload
# 需要导入模块: from googleapiclient import http [as 别名]
# 或者: from googleapiclient.http import MediaFileUpload [as 别名]
def initialize_upload(self, youtube, options):
tags = None
if options.keywords:
tags = options.keywords.split(",")
body = dict(
snippet = dict(
title = options.title,
description = options.description,
tags = tags,
categoryId = options.category
),
status = dict(
privacyStatus = options.privacy_status
)
)
insert_request = youtube.videos().insert(
part = ",".join(body.keys()),
body = body,
media_body = MediaFileUpload(options.file, chunksize = -1, resumable = True)
)
self.resumable_upload(insert_request)
示例3: _upload_to_gcs
# 需要导入模块: from googleapiclient import http [as 别名]
# 或者: from googleapiclient.http import MediaFileUpload [as 别名]
def _upload_to_gcs(gcs_services, local_file_name, bucket_name, gcs_location):
logging.info('Uploading file {} to {}...'.format(
local_file_name, "gs://{}/{}".format(bucket_name, gcs_location)))
media = MediaFileUpload(local_file_name,
mimetype='application/octet-stream',
chunksize=CHUNKSIZE, resumable=True)
request = gcs_services.objects().insert(
bucket=bucket_name, name=gcs_location, media_body=media)
response = None
while response is None:
progress, response = request.next_chunk()
logging.info('File {} uploaded to {}.'.format(
local_file_name, "gs://{}/{}".format(bucket_name, gcs_location)))
示例4: __insert_file
# 需要导入模块: from googleapiclient import http [as 别名]
# 或者: from googleapiclient.http import MediaFileUpload [as 别名]
def __insert_file(self):
print '[+] uploading file...'
media_body = MediaFileUpload(
self.info['path'], mimetype=self.info['mime_type'], resumable=True)
body = {
'title': self.info['name'],
'description': 'uploaded with packtpub-crawler',
'mimeType': self.info['mime_type'],
'parents': [{'id': self.__get_folder()}]
}
file = self.__googledrive_service.files().insert(body=body, media_body=media_body).execute()
# log_dict(file)
print '[+] updating file permissions...'
permissions = {
'role': 'reader',
'type': 'anyone',
'value': self.__config.get('googledrive', 'googledrive.gmail')
}
self.__googledrive_service.permissions().insert(fileId=file['id'], body=permissions).execute()
# self.__googledrive_service.files().get(fileId=file['id']).execute()
self.info['id'] = file['id']
self.info['download_url'] = file['webContentLink']
示例5: upload_file
# 需要导入模块: from googleapiclient import http [as 别名]
# 或者: from googleapiclient.http import MediaFileUpload [as 别名]
def upload_file(name, path, pid):
token = os.path.join(dirpath, 'token.json')
store = file.Storage(token)
creds = store.get()
service = build('drive', 'v3', http=creds.authorize(Http()))
file_mimeType = identify_mimetype(name)
file_metadata = {
'name': name,
'parents': [pid],
'mimeType': file_mimeType
}
media = MediaFileUpload(path, mimetype=file_mimeType)
new_file = service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
data = drive_data()
data[path] = {'id': new_file['id'], 'time': time.time()}
drive_data(data)
click.secho("uploaded " + name, fg='yellow')
return new_file
示例6: upload_file
# 需要导入模块: from googleapiclient import http [as 别名]
# 或者: from googleapiclient.http import MediaFileUpload [as 别名]
def upload_file(self,
file_location,
account_id,
web_property_id,
custom_data_source_id,
mime_type='application/octet-stream',
resumable_upload=False):
"""Uploads file to GA via the Data Import API
:param file_location: The path and name of the file to upload.
:type file_location: str
:param account_id: The GA account Id to which the data upload belongs.
:type account_id: str
:param web_property_id: UA-string associated with the upload.
:type web_property_id: str
:param custom_data_source_id: Custom Data Source Id to which this data
import belongs.
:type custom_data_source_id: str
:param mime_type: Label to identify the type of data in the HTTP request
:type mime_type: str
:param resumable_upload: flag to upload the file in a resumable fashion,
using a series of at least two requests
:type resumable_upload: bool
"""
media = MediaFileUpload(file_location,
mimetype=mime_type,
resumable=resumable_upload)
logger.info('Uploading file to GA file for accountId:%s,'
'webPropertyId:%s'
'and customDataSourceId:%s ',
account_id, web_property_id, custom_data_source_id)
# TODO(): handle scenario where upload fails
self.get_service().management().uploads().uploadData(
accountId=account_id,
webPropertyId=web_property_id,
customDataSourceId=custom_data_source_id,
media_body=media).execute()
示例7: upload_file
# 需要导入模块: from googleapiclient import http [as 别名]
# 或者: from googleapiclient.http import MediaFileUpload [as 别名]
def upload_file(self, local_location: str, remote_location: str) -> str:
"""
Uploads a file that is available locally to a Google Drive service.
:param local_location: The path where the file is available.
:type local_location: str
:param remote_location: The path where the file will be send
:type remote_location: str
:return: File ID
:rtype: str
"""
service = self.get_conn()
directory_path, _, filename = remote_location.rpartition("/")
if directory_path:
parent = self._ensure_folders_exists(directory_path)
else:
parent = "root"
file_metadata = {"name": filename, "parents": [parent]}
media = MediaFileUpload(local_location)
file = (
service.files() # pylint: disable=no-member
.create(body=file_metadata, media_body=media, fields="id")
.execute(num_retries=self.num_retries)
)
self.log.info("File %s uploaded to gdrive://%s.", local_location, remote_location)
return file.get("id")
示例8: upload_data
# 需要导入模块: from googleapiclient import http [as 别名]
# 或者: from googleapiclient.http import MediaFileUpload [as 别名]
def upload_data(
self,
file_location: str,
account_id: str,
web_property_id: str,
custom_data_source_id: str,
resumable_upload: bool = False,
) -> None:
"""
Uploads file to GA via the Data Import API
:param file_location: The path and name of the file to upload.
:type file_location: str
:param account_id: The GA account Id to which the data upload belongs.
:type account_id: str
:param web_property_id: UA-string associated with the upload.
:type web_property_id: str
:param custom_data_source_id: Custom Data Source Id to which this data import belongs.
:type custom_data_source_id: str
:param resumable_upload: flag to upload the file in a resumable fashion, using a
series of at least two requests.
:type resumable_upload: bool
"""
media = MediaFileUpload(
file_location,
mimetype="application/octet-stream",
resumable=resumable_upload,
)
self.log.info(
"Uploading file to GA file for accountId: %s, webPropertyId:%s and customDataSourceId:%s ",
account_id,
web_property_id,
custom_data_source_id,
)
self.get_conn().management().uploads().uploadData( # pylint: disable=no-member
accountId=account_id,
webPropertyId=web_property_id,
customDataSourceId=custom_data_source_id,
media_body=media,
).execute()
示例9: upload_file
# 需要导入模块: from googleapiclient import http [as 别名]
# 或者: from googleapiclient.http import MediaFileUpload [as 别名]
def upload_file(storage_service,bucket,bucket_path,file_name,verbose=True):
'''get_folder will return the folder with folder_name, and if create=True,
will create it if not found. If folder is found or created, the metadata is
returned, otherwise None is returned
:param storage_service: the drive_service created from get_storage_service
:param bucket: the bucket object from get_bucket
:param file_name: the name of the file to upload
:param bucket_path: the path to upload to
'''
# Set up path on bucket
upload_path = "%s/%s" %(bucket['id'],bucket_path)
if upload_path[-1] != '/':
upload_path = "%s/" %(upload_path)
upload_path = "%s%s" %(upload_path,os.path.basename(file_name))
body = {'name': upload_path }
# Create media object with correct mimetype
if os.path.exists(file_name):
mimetype = sniff_extension(file_name,verbose=verbose)
media = http.MediaFileUpload(file_name,
mimetype=mimetype,
resumable=True)
request = storage_service.objects().insert(bucket=bucket['id'],
body=body,
predefinedAcl="publicRead",
media_body=media)
result = request.execute()
return result
bot.warning('%s requested for upload does not exist, skipping' %file_name)
示例10: _upload_file_to_object
# 需要导入模块: from googleapiclient import http [as 别名]
# 或者: from googleapiclient.http import MediaFileUpload [as 别名]
def _upload_file_to_object(self, local_file_path: str, bucket_name: str,
object_name: str):
"""Upload the contents of a local file to an object in a GCS bucket."""
media_body = http.MediaFileUpload(local_file_path)
body = {'name': object_name}
request = self._storage_service.objects().insert(bucket=bucket_name,
body=body,
media_body=media_body)
try:
response = request.execute(num_retries=5)
if 'name' not in response:
raise CloudStorageError(
'Unexpected responses when uploading file "{}" to '
'bucket "{}"'.format(local_file_path, bucket_name))
except errors.HttpError as e:
if e.resp.status == 403:
raise CloudStorageError(
'You do not have permission to upload files to '
'bucket "{}"'.format(bucket_name))
elif e.resp.status == 404:
raise CloudStorageError(
'Bucket "{}" not found.'.format(bucket_name))
else:
raise CloudStorageError(
'Unexpected error when uploading file "{}" to '
'bucket "{}"'.format(local_file_path, bucket_name)) from e
# http.MediaFileUpload opens a file but never closes it. So we
# need to manually close the file to avoid "ResourceWarning:
# unclosed file".
# TODO: Remove this line when
# https://github.com/googleapis/google-api-python-client/issues/575
# is resolved.
media_body.stream().close()
示例11: upload
# 需要导入模块: from googleapiclient import http [as 别名]
# 或者: from googleapiclient.http import MediaFileUpload [as 别名]
def upload(self, bucket, object, filename, mime_type='application/octet-stream'):
"""
Uploads a local file to Google Cloud Storage.
:param bucket: The bucket to upload to.
:type bucket: str
:param object: The object name to set when uploading the local file.
:type object: str
:param filename: The local file path to the file to be uploaded.
:type filename: str
:param mime_type: The MIME type to set when uploading the file.
:type mime_type: str
"""
service = self.get_conn()
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
# pylint:disable=redefined-builtin
示例12: _upload_drive_image
# 需要导入模块: from googleapiclient import http [as 别名]
# 或者: from googleapiclient.http import MediaFileUpload [as 别名]
def _upload_drive_image(self, key, value, retry=True):
try:
file_metadata = {'name': key, 'parents': [self.drive_folder_id]}
media = MediaFileUpload(value, mimetype='image/png')
file = self.drive.files().create(body=file_metadata, media_body=media, fields='id').execute()
return file.get('id')
except HttpError as e:
if not retry:
raise e
self.drive_folder_id = self._prepare_drive_directory()
self._upload_drive_image(key, value, retry=False)
示例13: upload_file
# 需要导入模块: from googleapiclient import http [as 别名]
# 或者: from googleapiclient.http import MediaFileUpload [as 别名]
def upload_file(http, file_path, file_name, mime_type, event):
# 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 github.com/mkaraniya/BotHub.",
"mimeType": mime_type,
}
if parent_id:
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
while response is None:
status, response = file.next_chunk()
await asyncio.sleep(5)
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))
await event.edit(f"Uploading to Google Drive...\n\nFile Name: {file_name}\n{progress_str}")
if file:
await event.edit(file_name + " Uploaded Successfully")
# Insert new permissions
drive_service.permissions().insert(fileId=response.get('id'), body=permissions).execute()
# Define file instance and get url for download
file = drive_service.files().get(fileId=response.get('id')).execute()
download_url = response.get("webContentLink")
return download_url
示例14: __upload_empty_file
# 需要导入模块: from googleapiclient import http [as 别名]
# 或者: from googleapiclient.http import MediaFileUpload [as 别名]
def __upload_empty_file(self, path, file_name, mime_type, parent_id=None):
media_body = MediaFileUpload(path,
mimetype=mime_type,
resumable=False)
file_metadata = {
'name': file_name,
'description': 'mirror',
'mimeType': mime_type,
}
if parent_id is not None:
file_metadata['parents'] = [parent_id]
return self.__service.files().create(supportsTeamDrives=True,
body=file_metadata, media_body=media_body).execute()
示例15: store_file_from_disk
# 需要导入模块: from googleapiclient import http [as 别名]
# 或者: from googleapiclient.http import MediaFileUpload [as 别名]
def store_file_from_disk(self, key, filepath, metadata=None, # pylint: disable=arguments-differ, unused-variable
*, multipart=None, extra_props=None, # pylint: disable=arguments-differ, unused-variable
cache_control=None, mimetype=None):
mimetype = mimetype or "application/octet-stream"
upload = MediaFileUpload(filepath, mimetype, chunksize=UPLOAD_CHUNK_SIZE, resumable=True)
return self._upload(upload, key, self.sanitize_metadata(metadata), extra_props, cache_control=cache_control)