通过Python获取来自YouTube Google API的用户信息(API v3)

时间:2014-09-22 18:27:41

标签: python django google-api youtube-api

我是Google API的新手,但取得了一些进展;我有一个Django应用程序,它正在获取用户视频上传的列表。这很棒!我从Google提供的文档和示例中获取了所有内容。

我希望能够获取与其授权的YouTube帐户相关联的用户个人资料信息(因为我网站上的用户可能拥有多个YouTube帐户,我需要告知他们分开)。

这是我正在使用的简化版本:

YOUTUBE_READONLY_SCOPE = "https://www.googleapis.com/auth/youtube.readonly"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

# added this to increase the scope
GOOGLE_USER_INFO_SCOPE = "https://www.googleapis.com/auth/userinfo.profile"

FLOW = flow_from_clientsecrets(
    CLIENT_SECRETS,
    scope=[ YOUTUBE_READONLY_SCOPE, GOOGLE_USER_INFO_SCOPE ],
    redirect_uri='http://127.0.0.1:8000/youtube/oauth2callback')

@login_required
def index(request):
    storage = Storage(CredentialsModel, 'id', request.user, 'credential')
    credential = storage.get()

    http = httplib2.Http()
    http = credential.authorize(http)

    # gets a workable YouTube service!
    service = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, http=http)

    # how do I get the user name or email or other profile information here?

阅读this post之后,我知道我不能只使用userinfo = build('userinfo', "v2", http=http) ...但我对下次做的事情感到有些困惑。我看了this example,但它似乎使用了不同的库(我安装了google-api-python-client)。

我是否需要安装其他库(gdata库)才能获取用户信息?或者用户信息隐藏在我可以拨打build的其他服务中(例如Google+服务)?

1 个答案:

答案 0 :(得分:2)

因此必须添加额外的范围,它是Google Plus API的一部分。这是我添加的范围:

GOOGLE_PLUS_SCOPE = "https://www.googleapis.com/auth/plus.me"
GOOGLE_PLUS_SERVICE_NAME = "plus"
GOOGLE_PLUS_VERSION = "v1"

以下是我同时做两个范围的方法:

FLOW = flow_from_clientsecrets(
    CLIENT_SECRETS,
    scope=[ GOOGLE_PLUS_SCOPE, YOUTUBE_READONLY_SCOPE ],
    redirect_uri='http://127.0.0.1:8000/youtube/oauth2callback')

最后,这是我如何获得有关登录用户的信息:

userservice = build(GOOGLE_PLUS_SERVICE_NAME, GOOGLE_PLUS_VERSION, http=http)
userpeople = userservice.people()
me = userpeople.get(userId="me").execute()

print(me)

有一点需要指出的是,我必须启用Google+ API以及通讯录API。我不知道为什么但是在启用Contacts API之前这不起作用。