【发布时间】:2018-08-08 07:11:45
【问题描述】:
我在一些脚本中使用了 Google API 服务并且遇到了一些问题。这个错误很奇怪,但我们开始了。 我有一个列出我的 Google Drive 文件的脚本。
from apiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
SCOPES = 'https://www.googleapis.com/auth/drive.readonly.metadata'
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)
DRIVE = discovery.build('drive', 'v3', http=creds.authorize(Http()))
files = DRIVE.files().list().execute().get('files', [])
for f in files:
print(f['name'], f['mimeType'],f['id'])
效果很好,我从 Google API 下载 client_secret.json 并将其保存在同一个文件夹中,然后我启动脚本检查一切是否正常。
然后我开始编辑我的文件以更改我执行它的方式并且不读取文件,而是调用脚本并发送 client_id 和 client_secret 脚本的字符串,最终版本是这样的:
import sys
from apiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
# ID and SECRET arguments
client_id = sys.argv[1]
client_secret = sys.argv[2]
SCOPES = 'https://www.googleapis.com/auth/drive.readonly.metadata'
def listFiles(drive):
"""Receive the service and list the files"""
files = drive.files().list().execute().get('files', [])
for f in files:
print(f['name'], f['mimeType'],f['id'])
def main():
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.OAuth2WebServerFlow(client_id, client_secret, SCOPES)
creds = tools.run_flow(flow, store, tools.argparser.parse_args())
DRIVE = discovery.build('drive', 'v3', http=creds.authorize(Http()))
listFiles(DRIVE)
if __name__ == "__main__":
main()
我第一次启动这个新版本的脚本时它可以工作,因为旧版本中的脚本已经创建了storage.json 文件。
然后我将我的新版本脚本移动到另一个文件夹或机器(storage.json 文件不存在)以检查它是否有效,然后我得到这个:
$ python3 drive_list.py asdasdasdsa jijfkljflksdjflksdj
/usr/local/lib/python3.4/dist-packages/oauth2client/_helpers.py:255: UserWarning: Cannot access storage.json: No such file or directory
warnings.warn(_MISSING_FILE_MESSAGE.format(filename))
usage: drive_list.py [--auth_host_name AUTH_HOST_NAME]
[--noauth_local_webserver]
[--auth_host_port [AUTH_HOST_PORT [AUTH_HOST_PORT ...]]]
[--logging_level {DEBUG,INFO,WARNING,ERROR,CRITICAL}]
drive_list.py: error: unrecognized arguments: asdasdasdsa jijfkljflksdjflksdj
关于 storage.json 文件的警告是正常的,并且出现在两个脚本版本中,是 oauth2client 的一部分。
这是古玩部分,为什么当storage.json 文件存在时会识别参数(仅创建读取client_secret.json)?如果脚本第一次启动它会创建文件。
这个错误真的很奇怪,我只是想找出到底发生了什么。
如果有人可以帮助我,我将非常感激。
【问题讨论】:
标签: python python-3.x google-api google-api-python-client oauth2client