2014-09-22 134 views
0

我刚刚接触Google API,但取得了一些进展;我有一个获取用户视频上传列表的Django应用程序。这很好用!我从Google提供的文档和示例中获取了所有内容。从Python获取YouTube用户信息Python中的Google API(API v3)

我希望能够获得与其授权的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

你是对的。您必须建立与Google+ API的连接才能获取用户信息。 – schillingt 2014-09-22 19:58:30

+0

我被带到Google SignIn页面,但我被重定向到一个包含以下链接的页面 - http://127.0.0.1:8000/accounts/google/login/callback/?state=VZKqChhvHjMQebvWAm9ZAToxNTE5NjQwNzEx&code=4% 2FAADSCktyJ5WdX8BqyugMaR2FXTPrqQU3d7SalVHII00m5yBngjrgcLNDHL9Crikxb5gNLHIWgQ8XX2R4e54ILgg# 此页面正在返回404.任何提示? 如果可能,我可以在Github或其他任何地方获得完整的代码或链接吗? – wadhwa94 2018-02-26 10:40:14

回答

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以及Contacts API。我不知道为什么,但在联系人API被启用之前,这不起作用。