简体   繁体   English

Google Drive API 服务帐户身份验证以使用 Python 上传图像文件并将其插入到复制的文档中

[英]Google Drive API Service Account authentication to upload and insert an image file to into copied doc using Python

Google Drive API docs are not super great at helping determine best way to authenticate using a service account that I can then upload a .png file to the Drive. Google Drive API 文档并不能很好地帮助确定使用服务帐户进行身份验证的最佳方式,然后我可以将 .png 文件上传到 Drive。 My end goal it so upload a .png file, copy a template doc, batch update that doc using text replace, and insert the newly uploaded .png image into that doc.我的最终目标是上传 .png 文件,复制模板文档,使用文本替换批量更新该文档,并将新上传的 .png 图像插入该文档。

Sample code below:示例代码如下:

from dotenv import load_dotenv
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload

def credentials_from_file():
  credentials = service_account.Credentials.from_service_account_file(
    os.getenv('SERVICE_ACCOUNT_FILE'), 
    scopes=os.getenv('SCOPES')
  )
  drive_service = build('drive', 'v3', credentials=credentials)
  return drive_service

def google_upload(drive_service, metadata_name, parents, permissions, file_path, mime_type):
  file_metadata = {'kind':'drive#file', 'name':metadata_name, 'parents':parents, 'permissions':permissions}
  media = MediaFileUpload(file_path, mimetype=mime_type)
  file = drive_service.files().create(body=file_metadata, media_body=media, fields='id', supportsAllDrives=True).execute()
  print('File ID: %s' % file.get('id'))

Implementation of Code代码实现

credentials = credentials_from_file()
drive_service = build('drive', 'v3', credentials=credentials)

metadata_name = custom_variables_png_table_img
parents = ['xxxx']
permissions = [{'kind':'drive#permission', 'emailAddress':os.getenv('EMAIL_ACCOUNT'), 'role':'owner'}]
file_path = custom_variables_png_table_img
mime_type = 'image/png'
google_upload(drive_service, metadata_name, parents, permissions, file_path, mime_type)

EDIT:编辑:

Looks like I forgot to actually write was the problem is.看起来我忘了写是问题所在。 It's two fold.这是双重的。

  1. I keep getting 2 errors when trying to run the google_upload() function which looks like an authentication error with the service account.尝试运行google_upload()函数时,我不断收到 2 个错误,该函数看起来像是服务帐户的身份验证错误。

Error #1: jwt_grant access_token = response_data["access_token"] KeyError: 'access_token'错误 #1: jwt_grant access_token = response_data["access_token"] KeyError: 'access_token'

The above exception was the direct cause of the following exception:上述异常是以下异常的直接原因:

Error #2: google.auth.exceptions.RefreshError: ('No access token in response.', {'id_token': 'xxx'})错误 #2: google.auth.exceptions.RefreshError: ('No access token in response.', {'id_token': 'xxx'})

  1. Permissions being properly set on the recently uploaded image file.在最近上传的图像文件上正确设置了权限。

The code you are using currently seams to be the same as what I have seen before.您当前使用的代码接缝与我之前看到的相同。

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials


SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
KEY_FILE_LOCATION = '<REPLACE_WITH_JSON_FILE_PATH_TO_FILE>'



def initialize_drive():
  """Initializes an Google Drive API V3 service object.

  Returns:
    An authorized Google Drive API V3 service object.
  """
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      KEY_FILE_LOCATION, SCOPES)

  # Build the service object.
  driveService = build('drive', 'v4', credentials=credentials)

  return driveService

You haven't mentioned what is wrong with your code however i can make a few guesses.您还没有提到您的代码有什么问题,但是我可以做出一些猜测。

The thing is that you mention you want to upload an image and the insert it into a document.问题是您提到要上传图像并将其插入到文档中。 You need to remember that the Google drive api is just a file storage api it can do more then that store files.您需要记住,Google Drive api 只是一个文件存储 api,它可以做的不仅仅是存储文件。

When you upload the file using the service account you need to remember that the service account is not you.当您使用服务帐户上传文件时,您需要记住服务帐户不是您。 So when you are uploading this file to this directory parents = ['xxxx'] where ever that directory is, either on the service accounts drive account or if this directory is one of your persona directories which you have shared with the service account.因此,当您将此文件上传到此目录时, parents = ['xxxx']该目录所在的位置,无论是在服务帐户驱动器帐户上,还是该目录是您与服务帐户共享的角色目录之一。 You may not have permissions to see this file.您可能无权查看此文件。

By calling permissions create after uploading your file you can grant your own personal account permissions to access the file as well.通过在上传文件后调用权限创建,您也可以授予您自己的个人帐户访问该文件的权限。

As for adding the image to a document.至于将图像添加到文档中。 well the only way google can help you with that is if it is a Google doc type document.好吧,谷歌可以帮助您的唯一方法是它是否是谷歌文档类型的文档。 Then you would need to go though the Google docs api which would then give you access to add things programmaticlly to a document.然后您需要通过Google docs api ,然后您可以访问以编程方式将内容添加到文档中。 I haven't used this API much so im not sure if it has the ability to add images to a document.我没有经常使用这个 API,所以我不确定它是否能够将图像添加到文档中。

You should be able to use the google docs api with your service account you will just need to create a docs service using the same creds you already have from google drive.您应该能够通过您的服务帐户使用 google docs api,您只需要使用您已经从 google drive 拥有的相同凭据创建一个 docs 服务。

 service = build('docs', 'v1', credentials=creds)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用服务帐户密钥的 Google Drive Python API 授权 - Google Drive Python API authorization using service account key 无法重命名服务器上的文件,然后通过服务帐户上传到谷歌驱动器 API - Can't rename file on server, then upload onto google drive API via service account 如何使用python Telegram Bot API将文件上传到Google驱动器 - How to upload a file to google drive using python Telegram Bot API 为什么在 Python 中使用 Google 地球引擎并通过服务帐户进行身份验证时,导出到驱动器的内容为空? - Why is the export to the Drive empty, when using Google Earth Engine in Python with authentication through service account? 如何使用服务帐户凭据将文件上传到Google云端硬盘 - How to upload file to google drive with service account credential Google云端硬盘api和服务帐户 - Google drive api and service account Python Google Drive API无法使用mediaFileUpload插入媒体文件 - Python Google drive API cannot insert media file using mediaFileUpload Google Drive API Python插入文件 - Google Drive API Python insert file 如何在Google的python API和驱动器上使用服务帐户? - How to use a service account with Google's python api and drive? 如何使用 python 使用驱动器 API 将文件上传到谷歌驱动器? - How do I upload file to google drive using drive API using python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM