0
私はGoogle App Engine上でPythonアプリケーションを実行しています。 oauthライブラリを使用せずにOauth 2認証を実行しようとしています。Flaskセッションでurlfetchコンテンツの割り当てが許可されない - 内部サーバーエラー
Googleの認証コード(アクセストークン)から返された情報を保存し、次のリクエストに送信するセッションが必要です。フラスコのセッションキーにJSONを保存しようとすると、私のアプリはデバッグ情報なしで内部サーバーエラーになります。私のコードは、Oauth2のWebサーバーアプリケーションのドキュメント(コードにリンクされているリンク)用に、実際にはGoogleのHTTP Restサンプルのコピー貼りです。
import logging
import flask
from flask import render_template, session
import json
import urllib
from google.appengine.api import urlfetch
#Code from https://developers.google.com/identity/protocols/OAuth2WebServer
app = flask.Flask(__name__)
CLIENT_ID = '[].apps.googleusercontent.com'
CLIENT_SECRET = '[]'
SCOPE = 'email'
REDIRECT_URI = 'https://[].appspot.com/oauthcallback'
#check for last oauth step, if not go to intermediate steps
@app.route('/')
def index():
if 'credentials' not in flask.session:
return flask.render_template('index.html')
credentials = json.loads(flask.session['credentials'])
if credentials['expires_in'] <= 0:
return flask.redirect(flask.url_for('oauthcallback'))
else:
headers = {'Authorization': 'Bearer {}'.format(credentials['access_token'])}
req_uri = 'https://www.googleapis.com/oauth2/v2/userinfo'
r = requests.get(req_uri, headers=headers)
return r.text
#ask user to sign in, send code to googleapi to get token
@app.route('/oauthcallback')
def oauthcallback():
if 'code' not in flask.request.args:
auth_uri = ('https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id={}&redirect_uri={}&scope={}').format(CLIENT_ID, REDIRECT_URI, SCOPE)
return flask.redirect(auth_uri)
else:
auth_code = flask.request.args.get('code')
data = {'code': auth_code, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'redirect_uri': REDIRECT_URI, 'grant_type': 'authorization_code'}
r = urlfetch.fetch("https://www.googleapis.com/oauth2/v4/token", payload=data, method="POST")
#return r.content #prints json
flask.session['credentials'] = r.content #breaks here
return flask.redirect(flask.url_for('index'))
if __name__ == '__main__':
import uuid
app.secret_key = str(uuid.uuid4())
app.debug = True
app.run()