웹이 아닌 Python 클라이언트에서 인증된 Google App Engine 서비스에 어떻게 액세스하나요?

StackOverflow https://stackoverflow.com/questions/101742

문제

Google App Engine 앱이 있습니다. http://mylovelyapp.appspot.com/페이지가 있습니다 - mylovelypage

현재 페이지에서는 다음과 같은 작업을 수행합니다. self.response.out.write('OK')

내 컴퓨터에서 다음 Python을 실행하면:

import urllib2
f = urllib2.urlopen("http://mylovelyapp.appspot.com/mylovelypage")
s = f.read()
print s
f.close()

"OK"가 인쇄됩니다.

문제는 내가 추가하면 login:required 앱의 yaml에서 이 페이지로

그러면 Google 계정 로그인 페이지의 HTML이 인쇄됩니다.

나는 "일반적인" 인증 접근 방식을 시도했습니다.예를 들어

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()

auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(None,
                          uri='http://mylovelyapp.appspot.com/mylovelypage',
                          user='billy.bob@gmail.com',
                          passwd='billybobspasswd')
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)

하지만 아무런 차이가 없습니다. 여전히 로그인 페이지의 HTML이 다시 표시됩니다.

난 노력 했어 Google의 ClientLogin 인증 API, 하지만 작동시킬 수 없습니다.

h = httplib2.Http()

auth_uri = 'https://www.google.com/accounts/ClientLogin'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
myrequest = "Email=%s&Passwd=%s&service=ah&source=DALELANE-0.0" % ("billy.bob@gmail.com", "billybobspassword")
response, content = h.request(auth_uri, 'POST', body=myrequest, headers=headers)

if response['status'] == '200':
    authtok = re.search('Auth=(\S*)', content).group(1)

    headers = {}
    headers['Authorization'] = 'GoogleLogin auth=%s' % authtok.strip()
    headers['Content-Length'] = '0'

    response, content = h.request("http://mylovelyapp.appspot.com/mylovelypage", 
                                  'POST', 
                                  body="", 
                                  headers=headers)

    while response['status'] == "302":        
        response, content = h.request(response['location'], 'POST', body="", headers=headers) 

    print content

일부 토큰을 올바르게 얻을 수 있는 것 같지만 'mylovelypage'를 호출할 때 헤더에서 토큰을 사용하려고 하면 여전히 로그인 페이지의 HTML이 반환됩니다.:-(

누구든지 도와주실 수 있나요?

제가 사용해도 될까요? GData 클라이언트 라이브러리 이런 짓을 하려고?내가 읽은 내용에서 앱 엔진 앱에 액세스 할 수 있어야한다고 생각하지만 App Engine에 대한 인증이 작동하는 데 더 이상 성공하지 못했습니다.

내가 시작하기 위해 검색 해야하는 샘플, 기사 또는 키워드에 대한 포인터는 대단히 감사 할 것입니다.

감사해요!

도움이 되었습니까?

해결책

App Engine에 데이터를 업로드하는 도구인 appcfg.py는 App Engine 서버에서 자신을 인증하기 위해 정확히 이 작업을 수행해야 합니다.관련 기능은 appengine_rpc.py로 추상화됩니다.간단히 말해서 해결책은 다음과 같습니다.

  1. 사용 Google 클라이언트로그인 API 인증 토큰을 얻으려면.appengine_rpc.py에서 이 작업을 수행합니다. _GetAuthToken
  2. App Engine 앱의 특수 URL로 인증 토큰을 보냅니다.그러면 해당 페이지는 쿠키와 302 리디렉션을 반환합니다.리디렉션을 무시하고 쿠키를 저장합니다.appcfg.py는 이 작업을 수행합니다. _GetAuthCookie
  3. 이후의 모든 요청에는 반환된 쿠키를 사용하세요.

당신은 또한보고 싶을 수도 있습니다 _인증, appcfg가 ClientLogin의 다양한 반환 코드를 처리하는 방법을 확인하고 _GetOpener, appcfg가 HTTP 리디렉션을 따르지 않는 urllib2 OpenerDirector를 생성하는 방법을 확인하세요.또는 실제로 필요한 거의 모든 작업을 수행하는 AbstractRpcServer 및 HttpRpcServer 클래스를 도매로 사용할 수도 있습니다.

다른 팁

답변을 주신 Arachnid에게 감사드립니다. 제안한 대로 작동했습니다.

다음 사람이 시도하는 데 도움이 될 수 있도록 간단한 코드 사본이 있습니다!

import os
import urllib
import urllib2
import cookielib

users_email_address = "billy.bob@gmail.com"
users_password      = "billybobspassword"

target_authenticated_google_app_engine_uri = 'http://mylovelyapp.appspot.com/mylovelypage'
my_app_name = "yay-1.0"



# we use a cookie to authenticate with Google App Engine
#  by registering a cookie handler here, this will automatically store the 
#  cookie returned when we use urllib2 to open http://currentcost.appspot.com/_ah/login
cookiejar = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
urllib2.install_opener(opener)

#
# get an AuthToken from Google accounts
#
auth_uri = 'https://www.google.com/accounts/ClientLogin'
authreq_data = urllib.urlencode({ "Email":   users_email_address,
                                  "Passwd":  users_password,
                                  "service": "ah",
                                  "source":  my_app_name,
                                  "accountType": "HOSTED_OR_GOOGLE" })
auth_req = urllib2.Request(auth_uri, data=authreq_data)
auth_resp = urllib2.urlopen(auth_req)
auth_resp_body = auth_resp.read()
# auth response includes several fields - we're interested in 
#  the bit after Auth= 
auth_resp_dict = dict(x.split("=")
                      for x in auth_resp_body.split("\n") if x)
authtoken = auth_resp_dict["Auth"]

#
# get a cookie
# 
#  the call to request a cookie will also automatically redirect us to the page
#   that we want to go to
#  the cookie jar will automatically provide the cookie when we reach the 
#   redirected location

# this is where I actually want to go to
serv_uri = target_authenticated_google_app_engine_uri

serv_args = {}
serv_args['continue'] = serv_uri
serv_args['auth']     = authtoken

full_serv_uri = "http://mylovelyapp.appspot.com/_ah/login?%s" % (urllib.urlencode(serv_args))

serv_req = urllib2.Request(full_serv_uri)
serv_resp = urllib2.urlopen(serv_req)
serv_resp_body = serv_resp.read()

# serv_resp_body should contain the contents of the 
#  target_authenticated_google_app_engine_uri page - as we will have been 
#  redirected to that page automatically 
#
# to prove this, I'm just gonna print it out
print serv_resp_body

ClientLogin이 작동하지 않는 경우 App Engine을 사용해 보세요. OAuth 지원.

저는 AppEngine이나 Google의 웹 API에 익숙하지 않지만 무차별 접근 방식의 경우 mechanize(http://wwwsearch.sourceforge.net/mechanize/) 클라이언트의 실제 작업을 시작하기 전에 로그인 프로세스를 간단히 살펴보겠습니다.

저는 Python 전문가도 아니고 앱 엔진 전문가도 아닙니다.하지만 샘플 앱을 따라해 보셨나요? http://code.google.com/appengine/docs/gettingstarted/usingusers.html.나는 에 하나를 만들었습니다 http://quizengine.appspot.com, Google 인증 등 모든 것이 잘 작동하는 것 같았습니다.제안일 뿐이지만 시작 안내서를 살펴보세요.제안이 순진하게 들리면 진정하십시오.:) 감사해요.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top