我的应用程序在谷歌注册,我已经启用了联系人API。在
在第一个视图中,我获得了访问令牌,并将用户重定向到Google确认页面,在该页面上,将提示用户授予其联系人的访问权限:
SCOPE = 'https://www.google.com/m8/feeds/'
CLIENT_ID = 'xxxxxxxx'
CLIENT_SECRET = 'xxxxxxxxx'
APPLICATION= 'example.com'
USER_AGENT = 'dummy-sample'
APPLICATION_REDIRECT_URI = 'http://example.com/oauth2callback/'
def import_contacts(request):
auth_token = gdata.gauth.OAuth2Token(
client_id=CLIENT_ID, client_secret=CLIENT_SECRET,
scope=SCOPE, user_agent=USER_AGENT)
authorize_url = auth_token.generate_authorize_url(
redirect_uri=APPLICATION_REDIRECT_URI)
return redirect(authorize_url)
如果用户单击“允许”,则谷歌重定向到我的处理程序,该处理程序将检索联系人:
^{pr2}$
正如您所看到的,我的问题是如何在第二个视图中获取auth\u令牌对象,因为这段代码在auth_token.get_access_token(url.query)
行失败。
我尝试过多个选项,比如将对象放入会话中,但没有成功,但它不可序列化。我也尝试了gdata.gauth.token_to_blob(auth_token)
,但是我只能检索令牌字符串,而不能检索对象。使用gdata.gauth.ae_save()
和{}似乎在某种程度上需要googleappengine。在
我看到的另一种方法是在第一个Django视图中使用访问令牌直接请求联系人,而不是用代码交换令牌:
r = requests.get('https://www.google.com/m8/feeds/contacts/default/full?access_token=%s&alt=json&max-results=1000&start-index=1' % (self.access_token))
但这并不是将用户重定向到google页面,这样他们就可以明确表示同意了。相反,它直接使用令牌作为凭据获取联系人。这是惯例吗?你怎么认为?我认为第一种方法是首选方法,但首先我必须设法获得auth_token对象。。在
Tags:
对象用户comclienttokenauth视图urlapplicationgoogle联系人页面重定向gdatagauth1条回答网友
1楼 ·
发布于 2023-03-06 23:31:07
最后,我能够序列化对象并将其放入会话中,这不是一个安全的方法,但至少它会为我指明正确的方向,以便我可以继续我与社交应用程序相关的业务逻辑。在
import gdata.contacts.client
def import_contacts(request):
auth_token = gdata.gauth.OAuth2Token(
client_id=CLIENT_ID, client_secret=CLIENT_SECRET,
scope=SCOPE, user_agent=USER_AGENT)
authorize_url = auth_token.generate_authorize_url(
redirect_uri=APPLICATION_REDIRECT_URI)
# Put the object in the sesstion
request.session['auth_token'] = gdata.gauth.token_to_blob(auth_token)
return redirect(authorize_url)
def oauth2callback(request):
code = request.GET.get('code', '')
redirect_url = 'http://myapp.com/oauth2callback?code=%s' % code
url = atom.http_core.ParseUri(redirect_url)
# Retrieve the object from the session
auth_token = gdata.gauth.token_from_blob(request.session['auth_token'])
# Here is the tricky part: we need to add the redirect_uri to the object in addition
auth_token.redirect_uri = APPLICATION_REDIRECT_URI
# And this was my problem in my question above. Now I have the object in the handler view and can use it to retrieve the contacts.
auth_token.get_access_token(url.query)
# The second change I did was to create a ContactsClient instead of ContactsService
client = gdata.contacts.client.ContactsClient(source=APPLICATION)
auth_token.authorize(client)
feed = client.GetContacts()
all_emails = []
for i, entry in enumerate(feed.entry):
# Loop and fill the list with emails here
...
return render_to_response('xxx/import_contacts.html', {'all_emails': all_emails},
context_instance=RequestContext(request))