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

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

问题描述

我需要为网站的不同用户提供一些功能,以自动将html文件上传到Google磁盘,然后将其打开以在Google文档中进行查看和编辑.为此,我创建了一个文档,将其传递到google磁盘,并使用创建的文档的ID在google docs中打开它.
要访问api,我使用从服务Google帐户获取的json文件.我尝试使用所有者 view 权限执行代码,但是结果是相同的.

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来实现这一目标.
  • 我可以了解您的上述情况.您的问题有2个问题.

    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云端硬盘中创建.这样,该文件将无法在您的Google云端硬盘中看到.我认为这是您问题1的答案.而且,无法直接访问在服务帐户的Google云端硬盘中创建的文件,因为只有服务帐户才能访问该文件.我认为这是您问题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云端硬盘上查看创建的Google文档,并使用户查看和编辑创建的Google文档,我建议使用权限:在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,为了使用户查看和编辑创建的文档,将权限添加为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天全站免登陆