【问题标题】:PYTHON downloading google drive spreadsheetPYTHON 下载谷歌驱动器电子表格
【发布时间】:2023-03-13 05:26:02
【问题描述】:

我正在尝试使用 python 访问 google api 以从 google drive 下载电子表格,我从 google api 示例中借用了代码并对其进行了一些更改。但是,每次我运行时,我总是有这个 httpError 返回说我有“权限不足”。我在下面附上了我的代码,我想知道是否有人可以看看它并让我知道哪一部分是错误的。谢谢

import httplib2
import os
from apiclient.http import MediaIoBaseDownload
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
import io

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

SCOPES = 'https://www.googleapis.com/auth/drive'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Drive API Python Quickstart'

def get_credentials():

    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'drive-python-quickstart.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def main():

    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive', 'v3', http=http)
    file_id = '1tRL7q2AYdQuuaWQyfT700H3WG6Klod9EtjF2yTMoGiE'
    request = service.files().export_media(fileId=file_id,
                                                 mimeType='text/csv')
    fh = io.FileIO('LISAtrial.csv')
    downloader = MediaIoBaseDownload(fh, request)
    done = False
    while done is False:
        status, done = downloader.next_chunk()


if __name__ == '__main__':
    main()

【问题讨论】:

    标签: google-drive-api


    【解决方案1】:

    您可能需要检查用户访问文件的权限。在 Google Drive API V3 的Handling API Errors 文档中,

    403:文件权限不足。用户对文件 {fileId} 没有足够的权限。

    {
    "error": {
    "errors": [
    {
    "domain": "global",
    "reason": "insufficientFilePermissions",
    "message": "The user does not have sufficient permissions for file {fileId}."
    }
    ],
    "code": 403,
    "message": "The user does not have sufficient permissions for file {fileId}."
    }
    }
    

    您可能还想检查files.get 检索到的元数据中的用户访问级别,并使用它来将您的 UI 更改为只读 UI。

    Scopes 的用户许可和不当使用可能导致Insufficient Permission 响应。

    这里有一些相关的 SO 问题:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-06
      • 1970-01-01
      相关资源
      最近更新 更多