使用oauth2和Google API无法识别的参数 [英] Unrecognized arguments using oauth2 and Google APIs

查看:109
本文介绍了使用oauth2和Google API无法识别的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在某些脚本中使用Google API服务,但遇到了一些问题.这个错误有点怪异,但是我们开始吧. 我有一个列出我的Google云端硬盘文件的脚本.

I'm using the Google API services in some scripts and having some problems. This error is something weird, but here we go. I have a script that is listing my Google Drive files.

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并将其保存在同一文件夹中,然后启动脚本检查一切正常.

It works perfectly, I download the client_secret.json from Google API and save it in the same folder, then I start the script to check everythings is ok.

然后,我开始编辑文件以更改执行方式和不读取文件的方式,而是调用脚本并发送 client_id client_secret 脚本的字符串,最终版本是这样:

Then I start to edit my file to change the way how I execute it and don't read a file, instead, call the script and send the client_id and client_secret strings to the script, and the final version is this:

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文件不存在)以检查其是否有效,然后得到以下提示:

The first time that I start this new version of the script it works, because the script in the old version has created the storage.json file. Then I move my new version script to another folder or machine (where the storage.json file doesn't exists) to check if it works and then I get this:

$ 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时创建)?如果脚本第一次启动,它将创建文件. 这个错误真的很奇怪,我只是想找出正在发生的事情. 如果有人可以帮助我,我将非常感激.

This is the curios part, why the arguments are recognized when the storage.json file exists (ONLY created reading the client_secret.json)? if the first time that the script start it creates the file. Is really weird this error, and I'm just trying to find what is happening exactly. If someone can help me, I will be really thankful.

推荐答案

之所以发生这种情况,是因为您要导入oauth2client.tools模块.

This is happening because you are importing the oauth2client.tools module.

要正常工作,此模块依赖于标准的 argparse 模块.如果您不知道,该标准模块用于编写用户友好的命令行界面,并轻松管理命令行参数.这与您使用sys.argv[1]sys.argv[2]参数的情况不符.

To work correctly this module relies on the standard argparse module. In case you don't know, this standard module is used to write user-friendly command-line interfaces with easy management of command line arguments. This does not get along with your usage of sys.argv[1] and sys.argv[2] arguments.

要解决此问题,可以像下面的示例一样向命令行添加新的参数.进行此修改后,您将可以像这样运行该工具

To work around this, you can add new arguments to the command line like in the sample below. With this modification you would then run the tool like this

python3 drive_list.py -ci "your_client_id" -cs "your_client_secret"

以下是您的代码经过略微修改以添加新的命令行参数的情况:

Here is your code slightly modified to add the new command line arguments:

import argparse
from apiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools

# ID and SECRET arguments as new command line parameters
# Here is where you extend the oauth2client.tools startnd arguments
tools.argparser.add_argument('-ci', '--client-id', type=str, required=True, help='The client ID of your GCP project')
tools.argparser.add_argument('-cs', '--client-secret', type=str, required=True,
                             help='The client Secret of your GCP project')

SCOPES = 'https://www.googleapis.com/auth/drive.readonly.metadata'


def list_files(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:
        # You want to be sure to parse the args to take in consideration the new parameters
        args = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
        flow = client.OAuth2WebServerFlow(args.client_id, args.client_secret, SCOPES)
        creds = tools.run_flow(flow, store, tools.argparser.parse_args())
    drive_sdk = discovery.build('drive', 'v3', http=creds.authorize(Http()))
    list_files(drive_sdk)


if __name__ == "__main__":
    main()

这篇关于使用oauth2和Google API无法识别的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆