получение «Недопустимые запросы [0] .createImage: доступ к предоставленному изображению был запрещен». при добавлении изображения с Google Drive на слайды Google. Ниже приведен фрагмент кода, который я пробовал, хотя заставляю изображение опубликовать c с помощью расширенного параметра общего доступа. служебная учетная запись имеет доступ к редактированию слайда. Я хочу добавить к нему изображение.
import section: add here the required dependencies
"""
# python build-in modules
import json
import time
import io
# external modules
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build
from apiclient.http import MediaFileUpload
# user modules
from via_types import BasePlugin
class GoogleSlidesPlugin(BasePlugin):
"""
this plugin allows to communicate with Google API and Google Spreadsheets
by using the already created credentials
"""
def __init__(self):
BasePlugin.__init__(self)
self.Scopes = ['https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive.readonly','https://www.googleapis.com/auth/presentations','https://www.googleapis.com/auth/presentations.readonly']
self.Creds = ServiceAccountCredentials.from_json_keyfile_name(
r'Libraries/credentials/lucky-dahlia-268410-c4c0c57c1908.json', self.Scopes)
self.service = build('slides', 'v1', credentials=self.Creds)
self.drive = build('drive', 'v3', credentials=self.Creds)
def add_images_to_gslides(self, args):
"""
Adds a new worksheet to a spreadsheet.
:param args: [0]: Presentation
[1]: images array Paths
[2]: slide number to insert images
:param uid: this value is automatically generated for groped steps
:return: the detail and status execution of plugin
"""
# start results to report to output
self.response.status = 'pass'
self.response.details = 'image/s was/were added to slides'
try:
# try to store the passed arguments0
presentation_id = args[0]
except Exception as e:
# if there is a missed argument the command is going to end its exec
# store the results to report in output
self.response.status = 'fail'
self.response.details = 'some argument was missed'
return self.response
try:
# open connection with an specific GSlide
presentation = self.service.presentations().get(presentationId=presentation_id).execute()
slides = presentation.get('slides')
print('The presentation contains {} slides:'.format(len(slides)))
for i, slide in enumerate(slides):
print('- Slide #{} contains {} elements.'.format(
i + 1, len(slide.get('pageElements'))))
IMG_FILE = args[1]
try :
print('** Searching for icon file')
rsp = self.drive.files().list(q="name='%s'" % IMG_FILE).execute().get('files')[0]
print(' - Found image %r' % rsp['name'])
IMAGE_URL = 'https://drive.google.com/uc?export=download&id=' + rsp['id']
#IMAGE_URL = 'https://drive.google.com/file/d/'+rsp['id']+ '/edit'
except Exception as e:
file_metadata = {'name': IMG_FILE}
media = MediaFileUpload(IMG_FILE, mimetype='image/png')
upload = self.drive.files().create(body=file_metadata, media_body=media, fields='webContentLink, id, webViewLink').execute()
fileId = upload.get('id')
IMAGE_URL = upload.get('webContentLink')
self.drive.permissions().create(fileId=fileId, body={'type': 'anyone','role': 'writer'}).execute()
print(IMAGE_URL)
requests = []
image_id = 'MyImage_02'
page_id = slide['objectId']
emu4M = {
'magnitude': 4000000,
'unit': 'EMU'
}
requests.append({
'createImage': {
'objectId': image_id,
'url': IMAGE_URL,
'elementProperties': {
'pageObjectId': page_id,
'size': {
'height': emu4M,
'width': emu4M
},
'transform': {
'scaleX': 1,
'scaleY': 1,
'translateX': 100000,
'translateY': 100000,
'unit': 'EMU'
}
}
}
})
body = {
'requests': requests
}
response = self.service.presentations() \
.batchUpdate(presentationId=presentation_id, body=body ).execute()
create_image_response = response.get('replies')[0].get('createImage')
print('Created image with ID: {0}'.format(
create_image_response.get('objectId')))
except Exception as e:
self.response.status = 'fail'
self.response.details = e
return self.response
if __name__ == '__main__':
# use_the_main_function_to_test_your_plugin_without_using_a_sequence
plugin_template = GoogleSlidesPlugin()
plugin_template.add_images_to_gslides([presentationID,'image.png'])
print(plugin_template.response.status,
plugin_template.response.details)