【问题标题】:Oauth2 lib cannot import name 'run'Oauth2 lib 无法导入名称“运行”
【发布时间】:2016-05-08 23:52:51
【问题描述】:

我正在编写连接到 Youtube API 的代码,我看到的示例使用 Oauthlib2 工具中的“运行”来运行身份验证流程。我的 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'

【问题讨论】:

    标签: python oauth-2.0


    【解决方案1】:

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

    from oauth2client import tools
    

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

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

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

    【讨论】:

    • 谢谢。它要求我提供标志参数,但我的程序不是基于命令行的。有解决方法吗? credentials = run_flow(flow, storage, ?)
    • 非常感谢,非常有用的答案,效果很好!
    猜你喜欢
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 2020-04-07
    • 1970-01-01
    • 2020-12-28
    相关资源
    最近更新 更多