我正在尝试从gmail导入联系人,如下所示,但我得到401.
我已经提到了我在评论中尝试过的步骤,请告诉我。
import oauth2 as oauth, requests, urllib, urlparse
GOOGLE_REQUEST_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetRequestToken'
GOOGLE_ACCESS_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetAccessToken'
GOOGLE_AUTHORIZE_URL = 'https://www.google.com/accounts/OAuthAuthorizeToken'
GOOGLE_GET_CONTACTS_URL = 'https://www.google.com/m8/feeds/contacts/default/full' \
'?alt=json&max-results=50&start-index=%s'
SCOPE_URLS = ['https://www.google.com/m8/feeds/']
GOOGLE_OAUTH_CONSUMER_KEY = 'ANON'
GOOGLE_OAUTH_CONSUMER_SECRET = 'ANON'
def get_params(oauth_callback):
"""
returns a url with proper scope for the google contact importer
"""
params = { 'oauth_callback': oauth_callback}
if SCOPE_URLS:
params['scope'] = ' '.join(SCOPE_URLS)
return urllib.urlencode(params)
def request_google_token(request):
"""
This function makes a request to the google oauth server for access token and secret, and redirects the client to authorize the scopes(contact in this case) required by the client.
"""
consumer = oauth.Consumer(GOOGLE_OAUTH_CONSUMER_KEY, GOOGLE_OAUTH_CONSUMER_SECRET)
client = oauth.Client(consumer)
GOOGLE_CALLBACK_URL = 'http://%s/google/oauth/cb/' % (request.META.get('HTTP_HOST'))
resp, content = client.request("%s?%s" % (GOOGLE_REQUEST_TOKEN_URL, get_params(GOOGLE_CALLBACK_URL)), method="GET")
token = dict(urlparse.parse_qsl(content))
# save the consumer and token in a session variable for further exchange.
request.session['consumer'] = consumer
request.session['token'] = token
OAUTH_TOKEN = token.get('oauth_token')
OAUTH_TOKEN_SECRET = token.get('oauth_token_secret')
AUTH_URL = "%s?oauth_token=%s" % (GOOGLE_AUTHORIZE_URL, OAUTH_TOKEN)
return redirect(AUTH_URL)
def fetch_data(request):
"""
This function with the help of oauth_verifier and secret makes a request to the
API server, which has the data of the user
"""
oauth_verifier = request.GET.get('oauth_verifier')
token = request.session.get('token')
token.set_verifier(oauth_verifier)
client = oauth.Client(request.session.get('consumer'), token)
start = 1
resp, content = client.request(GOOGLE_GET_CONTACTS_URL % start, "GET")
return HttpResponse(str(content))
我得到了401 -
ipdb> resp
{'status': '401', 'content-length': '11849', 'x-xss-protection': '1; mode=block', 'x-content-type-options': 'nosniff', 'expires': 'Mon, 22 Jul 2013 16:27:58 GMT', 'server': 'GSE', '-content-encoding': 'gzip', 'cache-control': 'private, max-age=0', 'date': 'Mon, 22 Jul 2013 16:27:58 GMT', 'x-frame-options': 'SAMEORIGIN', 'content-type': 'text/html; charset=utf-8'}
请让我知道,我错过了什么。