使用 python 的 Google API 文件权限 [英] Google API file permissions using python

查看:44
本文介绍了使用 python 的 Google API 文件权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为我网站的不同用户做一些功能来自动将 html 文件上传到谷歌磁盘并打开它们以在谷歌文档中查看和编辑.为此,我创建了一个文档,将其传递到谷歌磁盘并使用创建的文档的 ID 在谷歌文档中打开它.
为了访问 api,我使用了从服务 Google 帐户中获取的 json 文件.我尝试使用 ownerview 权限执行我的代码,但结果是一样的.

I need to do some functionality for different users of my site to automatically upload html files to google disk and open them for viewing and editing in google docs. To do this I create a document, pass it to google disk and use the id of the created document to open it in google docs.
To access api, I use a json file taken from the service Google account. I tried to execute my code with owner and view rights, but the result is the same.

class CvView(AuthorizedMixin, View):
    """Here I check if the file format is html, I temporarily save it on disk and pass it to the file_to_drive function (to save it to google disk and open it in google docs) and delete it from disk"""


    def get(self, request, employee_id, format_):
        """Returns employee's CV in format which is equal to `format_`
        parameter."""

        employee = get_object_or_404(Employee, pk=employee_id)
        user = request.user
        content_type, data = Cv(employee, format_, user).get()

        if isinstance(data, BytesIO):
            return FileResponse(
                data, as_attachment=True, filename=f'cv.{format_}',
                content_type=content_type)
        if content_type == 'text/html':
            try:
                name = uuid.uuid4().hex + '.html'
                with open(name, 'w+') as output:
                    output.write(str(data))
                return HttpResponseRedirect(file_to_drive(import_file=name))
            finally:
                os.remove(os.path.join(settings.BASE_DIR, name))
        return HttpResponse(data, content_type=content_type)

file_to_drive

from google.oauth2 import service_account
from django.conf import settings
from googleapiclient.discovery import build

SCOPES = [
    'https://www.googleapis.com/auth/documents',
    'https://www.googleapis.com/auth/drive',
]
ACCOUNT_FILE = os.path.join(settings.BASE_DIR, 'cv-base-gapi.json')
def file_to_drive(import_file=None):
    credentials=service_account.Credentials.from_service_account_file(ACCOUNT_FILE, scopes=SCOPES)
    service = build('drive', 'v3', credentials=credentials)
    file_metadata = {
        'name': 'My Report',
        'mimeType': 'application/vnd.google-apps.spreadsheet'
    }
    media = MediaFileUpload(import_file,
                            mimetype='text/html',
                            resumable=True)
    file = service.files().create(body=file_metadata,
                                        media_body=media,
                                        fields='id').execute()
    print('File ID: %s' % file.get('id'))
    return (f"https://docs.google.com/document/d/{file.get('id')}/edit")

它似乎有效,但有一个不明确的时刻.

And it seems to be working, but there's an unclear moment.

首先,我没有在 Google 磁盘上看到保存的文件,但是 print('File ID: %s' % file.get('id')) 行给出我是新文档的 ID.

First of all, I don't see the saved file on the Google disk, but the print('File ID: %s' % file.get('id')) line gives me the id of the new document.

第二个最重要的问题是我收到一条关于缺少查看文档的权限的消息.

And the second most important problem is that I get a message about the missing permissions to view the document.

推荐答案

  • 您想从 HTML 数据创建新的 Google 文档.
  • 您想让用户查看和编辑创建的 Google 文档.
  • 您在这种情况下使用服务帐户.
  • 您想使用带有 Python 的 google-api-python-client 来实现这一点.
  • 我能理解你上面的情况.你的问题有两个问题.

    I could understand about your situation like above. And your question has 2 questions.

    1. 您想知道在您的 Google 云端硬盘中无法看到创建的 Google 文档的原因.
    2. 您想知道打开创建的文档需要权限的原因.

    如果我的理解是正确的,这个答案怎么样?请将此视为多个答案之一.

    If my understanding is correct, how about this answer? Please think of this as just one of several answers.

    作为你这两个问题的主要原因,我认为使用服务帐户是原因.服务帐户与您自己的 Google 帐户不同.例如,当文件由服务帐户创建时,文件是在服务帐户的 Google Drive 中创建的.这样,您的 Google 云端硬盘中就无法看到该文件.我认为这就是您问题1的答案.而且,在服务帐户的Google Drive中创建的文件无法直接访问,因为只有服务帐户才能访问它.我想这就是你的问题 2 的答案.

    As the main reason of your both questions, I think the use of the service account is the reason. The service account is different from your own Google account. So for example, when the file is created by the service account, the file is created in the Google Drive of the service account. By this, the file cannot be seen at your Google Drive. I think that this is the answer of your question 1. And, the file created in the Google Drive of the service account cannot be directly accessed because only the service account can access to it. I think that this is the answer of your question 2.

    为了在您的 Google Drive 上看到创建的 Google 文档并让用户查看和编辑创建的 Google 文档,我想建议使用 Permissions: create in Drive API 为创建的 Google 文档添加权限.当这反映到您的脚本中时,它变成如下所示.

    In order to see the created Google Document on your Google Drive and make users view and edit the created Google Document, I would like to propose to add the permissions to the created Google Document using Permissions: create in Drive API. When this is reflected to your script, it becomes as follows.

    请按如下方式修改您的脚本.

    Please modify your script as follows.

    def file_to_drive(import_file=None):
        credentials=service_account.Credentials.from_service_account_file(ACCOUNT_FILE, scopes=SCOPES)
        service = build('drive', 'v3', credentials=credentials)
        file_metadata = {
            'name': 'My Report',
            'mimeType': 'application/vnd.google-apps.spreadsheet'
        }
        media = MediaFileUpload(import_file,
                                mimetype='text/html',
                                resumable=True)
        file = service.files().create(body=file_metadata,
                                            media_body=media,
                                            fields='id').execute()
        print('File ID: %s' % file.get('id'))
        return (f"https://docs.google.com/document/d/{file.get('id')}/edit")
    

    到:

    def file_to_drive(import_file=None):
        credentials=service_account.Credentials.from_service_account_file(ACCOUNT_FILE, scopes=SCOPES)
        service = build('drive', 'v3', credentials=credentials)
        file_metadata = {
            'name': 'My Report',
            'mimeType': 'application/vnd.google-apps.document'  # Modified
        }
        media = MediaFileUpload(import_file,
                                mimetype='text/html',
                                resumable=True)
        file = service.files().create(body=file_metadata,
                                            media_body=media,
                                            fields='id').execute()
        fileId = file.get('id')  # Added
        print('File ID: %s' % fileId)
    
        # --- I added below script.
        permission1 = {
            'type': 'user',
            'role': 'writer',
            'emailAddress': '###',  # Please set your email of Google account.
        }
        service.permissions().create(fileId=fileId, body=permission1).execute()
        permission2 = {
            'type': 'anyone',
            'role': 'writer',
        }
        service.permissions().create(fileId=fileId, body=permission2).execute()
        # ---
    
        return (f"https://docs.google.com/document/d/{file.get('id')}/edit")
    

    • 在此修改中,在创建 Google 文档后,将权限添加到创建的文档中.
      • permission1 下,您的帐户被添加为作者.这样,您就可以在 Google 云端硬盘中看到创建的文档.请在此处设置您的 Google 帐户电子邮件.
      • permission2,为了让用户查看和编辑创建的Document,权限被添加为anyone类型.这是一个测试用例.如果您想添加用户的电子邮件作为权限,请将它们设置为permission1.
        • In this modification, after the Google Document is created, the permissions are added to the created Document.
          • At permission1, your account is added as the writer. By this, you can see the created Document at your Google Drive. Please set your email of Google account here.
          • At permission2, in order to make users view and edit the created Document, the permission is added as anyone type. This is a test case. If you want to add the user's emails as the permissions, please set them like permission1.
            • 当您要创建 Google 文档时,请将 application/vnd.google-apps.spreadsheet 修改为 application/vnd.google-apps.document.但就您而言,当 text/html 转换为 application/vnd.google-apps.spreadsheet 时,它会自动转换为 application/vnd.google-apps.document.因为text/html只能转换为application/vnd.google-apps.document.
            • When you want to create Google Document, please modify application/vnd.google-apps.spreadsheet to application/vnd.google-apps.document. But in your case, when text/html is converted to application/vnd.google-apps.spreadsheet, it automatically converts to application/vnd.google-apps.document. Because text/html can be converted to only application/vnd.google-apps.document.

            如果我误解了您的问题并且这不是您想要的方向,我深表歉意.

            If I misunderstood your question and this was not the direction you want, I apologize.

            这篇关于使用 python 的 Google API 文件权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆