Oauth2 lib无法导入名称'run'

时间:2016-01-31 14:48:17

标签: python oauth-2.0

我编码连接到Youtube API,我看到的示例使用Oauthlib2工具中的“run”来运行auth流程。我的venv安装似乎有问题(我已经重新安装了4次)但它找不到运行...可能是版本问题?我可以导入库的其他部分,但不能导入.tools。

代码:

import httplib2
import os
import logging
from oauth2client import run
from oauth2client.file import Storage
# from oauth2client.client import AccessTokenRefreshError
from googleapiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from googleapiclient.errors import HttpError
import json

CLIENT_SECRETS_FILE = "client_secrets.json"
YOUTUBE_READ_WRITE_SCOPE = "https://www.googleapis.com/auth/youtube"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
MISSING_CLIENT_SECRETS_MESSAGE = "Missing client secrets file"


def authenticate():
    httplib2.debuglevel = 4
    flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
                                   scope=YOUTUBE_READ_WRITE_SCOPE,
                                   message=MISSING_CLIENT_SECRETS_MESSAGE)
    storage = Storage("%s-oauth2.json")
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        print('invalid credentials')
        credentials = run_flow(flow, storage)

    service = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
                    http=credentials.authorize(httplib2.Http()))

    tags = "classical music", "yehudi mehunin"
    body = dict(
        snippet=dict(
            title="some title",
            description="a  description",
            tags=tags,
            categoryId="4"
        ),
        status=dict(
            privacyStatus="Private"
        )
    )

    thingy = service.videos().insert(part=",".join(body.keys()), body=None, media_body=MediaFileUpload(
        "1977.mp4", mimetype="video/mp4", chunksize=1024 * 1024, resumable=False))

    thingy.execute()

authenticate()

错误:

Traceback (most recent call last): File "/home/xavier/Code/autotube/youtube3.py", line 4, in <module> from oauth2client import run ImportError: cannot import name 'run'

1 个答案:

答案 0 :(得分:17)

我强烈建议寻找当前oauth2client实现的最新示例。旧的run方法已于2015年8月从库中删除,并在工具模块中被run_flow()替换。像这样导入:

from oauth2client import tools

然后使用tools.run_flow()访问它。

更新:关于你的后续问题你应该以编程方式输入哪些标志,如果没有可用的命令args,诀窍是使用这样的空args列表:

flags = tools.argparser.parse_args(args=[])
creds = tools.run_flow(flow, storage, flags)