在烧瓶中使用oauth2库时无法访问会话

时间:2016-05-07 03:20:13

标签: python google-app-engine flask gcloud

我正在尝试这几周,试图消除我做的每一个愚蠢的错误(一个新手!)。这是我的应用程序工厂功能。我在谷歌应用程序引擎书应用程序教程和得到它的山雀和位和试图模具我自己的东西。我陷入了登录功能。我正在使用包结构。

from woles_search import search#this is blueprint object
from PTE import PTE#this is blueprint object
from Home import home#this is blueprint object
from flask import current_app, Flask, redirect, request, session, url_for,g
import json
import config
import logging
import httplib2
infouser=""#tried to make this variable global and pass it in it templates but didnt worked 

# [START include]
from oauth2client.contrib.flask_util import UserOAuth2

oauth2 = UserOAuth2()
# [END include]
#creates a app instance in main directory
def create_app(config):
    app=Flask(__name__)
    app.config.from_object(config)
    #app.config['SECRET-KEY']="secret"
    print app.config['SECRET_KEY']
    from app_folder.woles_search import search
    from app_folder.PTE import PTE
    from app_folder.Home import home
    with app.app_context():
        model = get_model()
        model.init_app(app)

    oauth2.init_app(
    app,
    scopes=['email', 'profile'],
    authorize_callback=_request_user_info) #configuring oauth

    app.register_blueprint(search,url_prefix="/search")
    app.register_blueprint(PTE,url_prefix="/PTE")
    app.register_blueprint(home,url_prefix="/home")

    return app

def get_model():
    model_backend = current_app.config['DATA_BACKEND']
    print model_backend
    if model_backend == 'datastore':
        from auth_package import model_datastore
        model = model_datastore
    else:
        raise ValueError(
            "No appropriate databackend configured. "
            "Please specify datastore, cloudsql, or mongodb")

    return model


    # [START request_user_info]
def _request_user_info(credentials):
    """
    Makes an HTTP request to the Google+ API to retrieve the user's basic
    profile information, including full name and photo, and stores it in the
    Flask session.
    """
    http = httplib2.Http()
    credentials.authorize(http)
    resp, content = http.request(
        'https://www.googleapis.com/plus/v1/people/me')

    if resp.status != 200:
        current_app.logger.error(
            "Error while obtaining user profile: %s" % resp)
        return None


    infouser = json.loads(content.decode('utf-8'))
    #current_app.logger.info(infouser)#this works
    session['profile'] = infouser
    current_app.logger.info(session['profile'])
    #this is a test for session,since it does not show up in templates,it works, get printed out in console 

这是主要的.py和app.yaml(复制并粘贴,没什么特别的) main.py

import config
from flask import render_template,current_app,session
from app_folder.app import create_app

app = create_app(config)
app.config.from_object(config)
print app.config['SECRET_KEY']


    # Add a logout handler.
@app.route('/logout')
def logout():
    # Delete the user's profile and the credentials stored by oauth2.
    del session['profile']
    oauth2.storage.delete()
    return redirect(request.referrer or '/')
    # [END logout]


@app.route('/')
def index():
    return render_template('base.html')</code>

这是app.yaml

runtime: python27
api_version: 1
threadsafe: yes
handlers:
- url: /.*  # This regex directs all routes to main.app
  script: main.app
ibraries:
- name: jinja2
  version: latest

这是模板

 <html lang="en">
  <head>
    <title>Bookshelf - Python on Google Cloud Platform</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
  </head>
  <body>
    <div class="navbar navbar-default">
      <div class="container">
        <div class="navbar-header">
          <div class="navbar-brand">Bookshelf</div>
        </div>
        <ul class="nav navbar-nav">
          <li><a href="/books">Books</a></li>
          <li><a href="/books/mine">My Books</a></li>
        </ul>
        {# [START profile] #}
        {{session.profile.displayName}}
        <p class="navbar-text navbar-right">
        {% if session.profile %}
          <a href="/logout">
            {% if session.profile.image %}
              <img class="img-circle" src="{{session.profile.image.url}}" width="24">
            {% endif %}
            {{session.profile.displayName}}
          </a>
        {% else %}
          <a href="/oauth2authorize">Login</a>
        {% endif %}
        </p>
        {# [END profile] #}
      </div>
    </div>
    <div class="container">
      {% block content %}{% endblock %}
    </div>
    {{user}}
  </body>
</html>
</code>

注意在if块之外使用{{session.profile.displayname}},这是为了查看错误是什么,但最终它在base.html中停止显示没有错误(??)但仍然显示注销视图中的错误抛出错误&#34;没有找到密钥配置文件&#34;。我可以在我的控制台输出中看到用户信息。我在root中有配置文件。我检查了它,它加载了google凭据和密钥我正在使用google cloud sdk shell,因为我的dev_appserver.py在gcloud sdk update之后在windows上的cmd中不再被识别。我撤销了云sdk shell上的凭据只是为了确保它不是干扰(如果它确实!!)和也试过,虽然它被授权。我尝试制作COOKIE_SECURE_PATH = False和很多我能想到但没有结果的东西。请帮助!!!

1 个答案:

答案 0 :(得分:1)

我有太多未解决的参考资料来测试您的代码。我建议你为小函数编写测试用例,如果可能的话,尝试使用另一个用于python appengine的oauth框架,如simpleauth,如果它对你有用https://github.com/crhym3/simpleauth我也很难使用高级登录框架,直到simpleauth工作才开始工作。有什么理由不使用它吗?我能帮你。你可以在这里阅读我关于Onguth的问题How to update User with webapp2 and simpleauth?