8

data.photos.service.PhotosService을 사용하여 Picasa에서 사진을 가져오고 당길 수 있습니다. 나는 Google 콘솔에서 서비스 키 파일 XXXXXXXX-privatekey.p12를 얻었으며 지금은 Google과 함께 키를 사용하여 인증을 시도하고 있습니다.python의 gdata에서 OAuth2 서비스 계정 사용

f = file(settings.SITE_ROOT + '/aurora/' + settings.PRIVATE_KEY, 'rb') 
key = f.read() 
f.close() 

credentials = SignedJwtAssertionCredentials(settings.SERVICE_ACCOUNT_NAME, key, scope = 'http://picasaweb.google.com/data https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile') 
http = httplib2.Http() 
http = credentials.authorize(http) 
service = build("oauth2", "v2", http=http) 
user_info = None 
try: 
    user_info = service.userinfo().get().execute() 
    # neither of these two methods work 
    #gd_client.SetOAuthInputParameters(signature_method = gdata.auth.OAuthSignatureMethod.RSA_SHA1, consumer_key = "asdfasdfasdf.apps.googleusercontent.com", rsa_key = key, two_legged_oauth = True, requestor_id = user_info.get('email')) 
    #gd_client.auth_token = gdata.gauth.TwoLeggedOAuthRsaToken(consumer_key = user_info.get('email'), rsa_private_key = key, requestor_id = user_info.get('email')) 
except errors.HttpError, e: 
    logging.error('An error occurred: %s', e) 

user_inf0 = {u'verified_email': True, u'id': u'1234', u'name': u'[email protected]', u'email': u'[email protected]'} 

문제는 방법 중 하나 SetOAuthInputParameters를 사용하여 2 리턴한다을 유효하지 않은 토큰, 또는 방법을 반환한다는 것입니다 :

OAUTH2 사용에서 appengine에 대한 문서는 다음을 사용하는 것이 유용 할 것이라고 믿고 저를 주도하고있다 403 restricted.

나는 지혜로운 끝에서 모든 사람들이 규칙적으로 3 발의 oauth 코드를 읽는 것을 정말로 읽고 정말로 그렇게하지 않으려 고합니다. 아직 보지 못한 아이디어 나 기사는 없습니까?

답변

19

gdata.gauth.OAuth2TokenFromCredentials를 사용하십시오.

auth2token = gdata.gauth.OAuth2TokenFromCredentials(credentials) 
gd_client = auth2token.authorize(gd_client) 

OAuth2TokenFromCredentials는 동시에 apiclient 및 GDATA를 사용할 수 있도록 설계되었습니다. 이 문서에서는 gdata 호출을 수행하는 데 필요한 인증 정보가 있는지 확인하기 위해 자격 증명을 사용합니다.

여전히 403이 나오면 완전히 다른 것일 수 있습니다. 나는 SignedJwtAssertionCredentials 호출에서 사용자를 적절히 지정하지 않았기 때문에 서비스 계정을 사용하여 사용자의 데이터에 액세스하고 403을 얻고있었습니다.

업데이트 :

from oauth2client.client import SignedJwtAssertionCredentials 
credentials = SignedJwtAssertionCredentials(
    "[email protected]", 
    open("keyfile").read(), 
    scope=(
        "https://www.googleapis.com/auth/drive", 
        "https://spreadsheets.google.com/feeds", 
        "https://docs.google.com/feeds" 
    ), # For example. 
    sub="[email protected]" 
) 
http = httplib2.Http() 
http = credentials.authorize(http) # Not needed? See comment below. 
auth2token = gdata.gauth.OAuth2TokenFromCredentials(credentials) 
gd_client = gdata.photos.service.PhotosService() # For example. 
gd_client = auth2token.authorize(gd_client) 
+0

어떻게 'SignedJwtAssertionCredentials' 호출에서 사용자를 지정 했습니까? – Gautam

+1

답변을 업데이트했습니다. –

+0

계속 HTTP 400을 받고 있는데 스프레드 시트 API를 사용하고 있습니다 – Gautam

0

Google 계정에서 MFA를 사용하는 경우, 당신은 동의 화면 인증 방법을 사용할 필요가 : 여기에 사용되는 기본 패턴입니다. Picassa API를 사용하면 요청 API가 약간 다르므로 그대로 작동하지 않습니다.

import gdata.gauth 
import os 
import pickle 
import gdata.photos.service 

clientid='xxx' # https://console.developers.google.com/apis/credentials 
clientsecret='xxx' 
Scope='https://picasaweb.google.com/data/' 
User_agent='myself' 

def GetAuthToken(): 
    if os.path.exists(".token"): 
     with open(".token") as f: 
      token = pickle.load(f) 
    else: 
     token = gdata.gauth.OAuth2Token(client_id=clientid,client_secret=clientsecret,scope=Scope,user_agent=User_agent) 
     print token.generate_authorize_url(redirect_uri='urn:ietf:wg:oauth:2.0:oob') 
     code = raw_input('What is the verification code? ').strip() 
     token.get_access_token(code) 
     with open(".token", 'w') as f: 
      pickle.dump(token, f) 
    return token 


token = GetAuthToken() 

gd_client = gdata.photos.service.PhotosService() 
old_request = gd_client.request 


def request(operation, url, data=None, headers=None): 
    headers = headers or {} 
    headers['Authorization'] = 'Bearer ' + token.access_token 
    return old_request(operation, url, data=data, headers=headers) 


gd_client.request = request 
photos = gd_client.GetUserFeed(kind='photo', limit='10') 
for photo in photos.entry: 
    print 'Recently added photo title:', photo.title.text