使用google api(python)在Google云端硬盘中搜索文件

时间:2017-06-21 08:55:58

标签: python google-api

我正在尝试搜索Google云端硬盘中的文件。我提供了文件名和文件ID,但它在drive_service中显示了一些错误。

这是我的代码:

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

我得到的错误是:

  

追踪(最近一次通话):         文件" searchfilev3.py",第27行,in           response = drive_service.files()。list(q =" mimeType =' image / jpeg'",       NameError:name' drive_service'未定义

2 个答案:

答案 0 :(得分:1)

  1. 您需要生成凭据以授权您的请求。见https://console.developers.google.com/apis/library。下面的代码使用您存储在client_secret.json中的服务帐户密钥。

    count

答案 1 :(得分:0)

您需要更改

DRIVE = build('drive', 'v3', http=creds.authorize(Http()))

drive_service = build('drive', 'v3', http=creds.authorize(Http()))

并更改

store = file.Storage('storage.json')

store = file.Storage('token.json')