使用谷歌搜索在谷歌驱动器中的文件api(python)
问题描述:
我想搜索我的Google云端硬盘中的文件。我给出了文件名和文件ID,但它在drive_service
中显示了一些错误。使用谷歌搜索在谷歌驱动器中的文件api(python)
这里是我的代码:
from __future__ import print_function
import os
import io
from apiclient.http import MediaIoBaseDownload
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
try:
import argparse
flags = \
argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = 'https://www.googleapis.com/auth/drive.file'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = (tools.run_flow(flow, store,
flags) if flags else tools.run(flow, store))
DRIVE = build('drive', 'v3', http=creds.authorize(Http()))
id = '0B1hy3tfpHf5WSkNLNFJXVS04Qlk'
name = 'hello.txt'
page_token = None
while True:
response = drive_service.files().list(q="mimeType='image/jpeg'",
spaces='drive', fields='nextPageToken, files(id, name)',
pageToken=page_token).execute()
for file in response.get('files', []):
# Process change
print('Found file: %s (%s)' % (file.get('name'), file.get('id'
)))
page_token = response.get('nextPageToken', None)
if page_token is None:
break
我得到的错误是:
Traceback (most recent call last): File "searchfilev3.py", line 27, in response = drive_service.files().list(q="mimeType='image/jpeg'", NameError: name 'drive_service' is not defined
答
-
你需要生成一个证书授权您的请求。看到这里https://console.developers.google.com/apis/library。以下代码使用您存储在client_secret.json中的服务帐户密钥。
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope) http = credentials.authorize(httplib2.Http()) drive_service = discovery.build('drive', 'v3', http=http)
你确定你使用了正确的API?你有没有试过[这个](https://developers.google.com/drive/v2/reference/files/get)? –
是的,我认为是......有什么不对吗? –
那里使用'service.files()'获取文件。也可以尝试使用:from apiclient import http'导入完整的'http'模块。 –