如何在Google Calendar API中使用run_flow()?

时间:2013-12-04 07:51:32

标签: python api google-api google-calendar-api

我正在尝试对使用the sample described in the docs的Google Calendar API进行身份验证:

from oauth2client import file
from oauth2client import client
from oauth2client import tools

CLIENT_SECRETS = 'client_secrets.json'
FLOW = client.flow_from_clientsecrets(CLIENT_SECRETS,
                                      scope=[
                                          'https://www.googleapis.com/auth/calendar',
                                          'https://www.googleapis.com/auth/calendar.readonly',
                                      ],
                                      message=tools.message_if_missing(CLIENT_SECRETS))

storage = file.Storage('sample.dat')
credentials = storage.get()
if credentials is None or credentials.invalid:
    credentials = tools.run_flow(FLOW, storage, auth_host_name='localhost', auth_host_port=[8080, 8090],
                                 logging_level='ERROR', noauth_local_webserver=False)

此代码以

失败
Traceback (most recent call last):
  File "C:/infoscreen/testgoogle.py", line 18, in <module>
    logging_level='ERROR', noauth_local_webserver=False)
  File "C:\infoscreen\oauth2client\util.py", line 132, in positional_wrapper
    return wrapped(*args, **kwargs)
TypeError: run_flow() got an unexpected keyword argument 'auth_host_name'

documentation for run-flow()

  

它假定它是从命令行应用程序运行并支持   以下标志:

     

- auth_host_name:运行本地Web服务器时使用的主机名       在OAuth授权期间处理重定向。       (默认:'localhost')

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:4)

run_flow()函数由命令行标志控制,必须初始化Python标准库argparse模块,以下显示如何使用它:

import argparse
from oauth2client import tools
from oauth2client.tools import run_flow
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.file import Storage

client_id = 'YOUR CLIENT IS HERE'
client_secret = 'YOU CLIENT SECRET IS HERE'
scope = 'https://www.googleapis.com/auth/calendar'

flow = OAuth2WebServerFlow(client_id, client_secret, scope)

parser = argparse.ArgumentParser(parents=[tools.argparser])
flags = parser.parse_args()

storage = Storage('credentials.dat')
#the get() function returns the credentials for the Storage object. 

credentials = storage.get()
if credentials is None or credentials.invalid:
  credentials = tools.run_flow(flow, storage, flags)

答案 1 :(得分:1)

我迟到了一个月,但我会试一试。

我查看了文档,并在标记部分下找到了这个:

The tools module defines an ArgumentParser the already contains the flag
definitions that run() requires. You can pass that ArgumentParser to your
ArgumentParser constructor:

parser = argparse.ArgumentParser(description=__doc__,
    formatter_class=argparse.RawDescriptionHelpFormatter,
    parents=[tools.run_parser])
flags = parser.parse_args(argv)

所以好像你不应该将标志作为参数添加,而是从命令行添加它们,然后使用Google的ArgumentParser返回一个“flags”对象,然后将其添加为第三个位置参数