错误:“无法识别的参数:shell” - Python的OAuth 2.0 Google API客户端

2 投票
3 回答
3114 浏览
提问于 2025-04-18 17:02

我正在尝试做一个纯服务器端的身份验证。我按照谷歌开发者提供的代码示例中的所有步骤来操作。问题是,execfile()在普通的python shell中运行得很好,但在python interactive shell中却出现了下面提到的错误。

以下是相关语句的日志。我需要在playlistitems.py文件中定义什么,才能在Python交互式Shell中执行它呢?

playlistitems.py的代码:示例代码

Kshitij:trailers_backend Kshitij$ python manage.py shell
Python 2.7.5 (default, Mar  9 2014, 22:15:05) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> execfile("playlistitems.py")
usage: manage.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}]
manage.py: error: unrecognized arguments: shell
Kshitij:trailers_backend Kshitij$ 

我通过直接修改tools.py中的值来传递参数。以下是我遇到的错误。我该如何解决这个问题?有没有一个完整的示例可以参考?

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/Kshitij/django project/trailers_backend/videoStore/getVideos.py", line 62, in getVideos
     credentials = run_flow(flow, storage, flags)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 1260, in add_argument
    if not args or len(args) == 1 and args[0][0] not in chars:
TypeError: 'bool' object has no attribute '__getitem__'
>>> 

3 个回答

0

你需要从OAuth2Client tools中为你的run_flow()方法传递一些参数。这个方法要求你在调用run_flow()时必须解析以下参数:

run_flow(flow, storage, flags, http=None)

你缺少的就是这些标志,你必须添加这些标志(在链接中有详细说明):

--auth_host_name: Host name to use when running a local web server
    to handle redirects during OAuth authorization.
    (default: 'localhost')

--auth_host_port: Port to use when running a local web server to handle
    redirects during OAuth authorization.;
    repeat this option to specify a list of values
    (default: '[8080, 8090]')
    (an integer)

--[no]auth_local_webserver: Run a local web server to handle redirects
    during OAuth authorization.
    (default: 'true')

不过我还没搞明白具体该怎么解析这些标志,遗憾的是,我现在有一个悬赏问题,想知道怎么模拟旧的run()方法来认证你的会话,详细内容可以在这里找到。

3

这个方法对我有效。首先,我从oauth2client这个库里导入了tools。然后,我用tools里的argparser来解析参数,传入一个空列表。这样做后,它会让我在浏览器里打开一个认证的网址。希望这个信息对你有帮助。

5

我终于在@Stormie的帮助下得到了可以运行的代码。下面是这个有效的代码片段。

if credentials is None or credentials.invalid:
    flags = argparser.parse_args('--auth_host_name localhost --logging_level INFO'.split())
    credentials = run_flow(flow, storage, flags)

我刚刚了解到parse_args()这个方法。parse_args()是ArgumentParser类中的一个方法,用来传递参数。

如果你是在命令行进行身份验证,而你的浏览器不支持Javascript,你可能需要添加这个参数 --noauth_local_webserver:

flags = argparser.parse_args('--auth_host_name localhost --logging_level INFO --noauth_local_webserver'.split())
        credentials = run_flow(flow, storage, flags)

撰写回答