(Web 以外の) 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 クライアント ライブラリ このようなことをするのですか?私が読んだことから、アプリエンジンアプリにアクセスできるはずだと思いますが、アプリエンジンのもので認証を機能させることに成功していません。

サンプル、記事、または私が私を始めるために探しているべきキーワードへのポインターは、非常に高く評価されます。

ありがとう!

役に立ちましたか?

解決

appcfg.py、App Engine にデータをアップロードするツールは、まさにこれを実行して、App Engine サーバーで自身を認証する必要があります。関連する機能は appengine_rpc.py に抽象化されます。一言で言えば、解決策は次のとおりです。

  1. 使用 Google クライアントログイン API 認証トークンを取得します。appengine_rpc.py はこれを実行します _GetAuthToken
  2. 認証トークンを App Engine アプリの特別な URL に送信します。その後、そのページは Cookie と 302 リダイレクトを返します。リダイレクトを無視して Cookie を保存します。appcfg.py はこれを実行します _GetAuthCookie
  3. 返された Cookie は、今後のすべてのリクエストで使用されます。

こちらもご覧ください _認証する, 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 が機能しない場合は、アプリ エンジンを試してください。 OAuthのサポート.

私は AppEngine や Google の Web 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