2016-09-06 99 views
0

我想使用Python來訪問谷歌的API,從谷歌驅動下載電子表格,我借用谷歌API示例代碼,並做了一些改變它。但是,每次運行時,我總是有這個httpError返回,說我有「權限不足」。我在下面附上我的代碼,我想知道是否有人可以看看它,並讓我知道哪個部分是錯的。謝謝PYTHON下載谷歌雲端硬盤電子表格

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() 

回答

0

您可能想要檢查用戶訪問文件的權限。在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問題:

相關問題