如何在 Google App Engine Python 应用程序上的模块之间共享会话? [英] How to share sessions between modules on a Google App Engine Python application?

查看:16
本文介绍了如何在 Google App Engine Python 应用程序上的模块之间共享会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Google App Engine Modules(https://developers.google.com/appengine/docs/python/modules/) 并且它们在模块之间共享会话信息:

模块:

  • 模块 1 - 登录页面:带有登录表单的基本页面,如果是有效用户,我将创建一个会话,然后将用户重定向到仪表板页面(模块 2)
  • 模块 2 - 仪表板页面:如果模块可以读取会话变量中的数据,则显示消息的页面

问题是在仪表板模块中,在登录页面(模块 1)中创建的会话数据不存在.

是否可以访问 Google App Engine 中两个或多个模块之间的会话数据?

来源:

baseHandler.py

导入 webapp2从 webapp2_extras 导入会话类 BaseHandler(webapp2.RequestHandler):def render_template(self, view_filename, params=None):参数 = {}path = os.path.join(os.path.dirname(__file__), 'views', view_filename)self.response.out.write(template.render(path, params))def display_message(self, message):"""显示带有简单消息的模板的实用函数."""参数 = {}self.render_template('message.html', params)def调度(自我):# 获取此请求的会话存储.self.session_store = session.get_store(request=self.request)尝试:# 发送请求.webapp2.RequestHandler.dispatch(self)最后:# 保存所有会话.self.session_store.save_sessions(self.response)@webapp2.cached_property定义会话(自我):# 使用默认 cookie 键返回会话.返回 self.session_store.get_session()

模块 1(登录)main.py

 from google.appengine.ext import ndb导入 webapp2从 webapp2_extras.security 导入 hash_password导入日志导入操作系统导入系统进口jinja2从 src.basehandler 导入 BaseHandler从 src.user 导入用户JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),extensions=['jinja2.ext.autoescape'])类 MainPage(BaseHandler):定义获取(自我):模板值 = {}template = JINJA_ENVIRONMENT.get_template('templates/index.html')self.response.write(template.render(template_values))定义帖子(自我):email_address = self.request.get('input-email')密码 = self.request.get('输入密码')密码 = hash_password(密码,'sha1',盐=无,胡椒=无)qry = User.query(ndb.AND(User.email_address == email_address,用户.密码 == 密码)).拿来()如果问:self.session['loggedin'] = Trueself.redirect('http://dashboard.myURL.appspot.com/')别的:self.redirect('/?error=invaliduser')配置 = {}配置['webapp2_extras.sessions'] = {'secret_key': 'my-super-secret-key',}app = webapp2.WSGIApplication([('/', 主页)],调试=真,配置=配置)

模块 2(仪表板)main.py

 from google.appengine.ext import ndb导入 webapp2导入日志导入操作系统导入系统进口jinja2从 src.basehandler 导入 BaseHandler从 src.user 导入用户JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),extensions=['jinja2.ext.autoescape'])类 Main(BaseHandler):定义获取(自我):味精 = ''如果不是 self.session.get('loggedin'):msg = '没有会话'别的:msg = '有一个会话'template_values = {'味精':味精}template = JINJA_ENVIRONMENT.get_template('templates/index.html')self.response.write(template.render(template_values))配置 = {}配置['webapp2_extras.sessions'] = {'secret_key': 'my-super-secret-key',}app = webapp2.WSGIApplication([('/', 主要的)],调试=真,配置=配置)

欢迎任何帮助,如有拼写错误,请见谅

解决方案

默认情况下 webapp2_extra.sessions 使用基于 cookie 的会话.这些将绑定到特定域.您的模块可能位于 module1.yourapp.appspot.com 和 module2.yourapp.appspot.com(猜测).第二个模块将无法看到第一个模块设置的 cookie.

在您的配置中尝试为 cookie 设置域.

config['webapp2_extras.sessions'] = {'secret_key': 'my-super-secret-key',cookie_args':{域":yourapp.appspot.com"}

文档说:

<块引用>

 - 域:cookie 的域.要跨子域工作域必须设置为主域,前面有一个点,例如,为`.mydomain.org` 设置的cookies 将在`foo.mydomain.org` 和`bar.mydomain.org`.默认为 None,这意味着 cookie 将仅适用于当前子域.

来自:https://code.google.com/p/webapp-改进/源/浏览/webapp2_extras/sessions.py

或者您也可以使用其他后端之一,如内存缓存或数据存储.如果您的会话包含敏感信息,这是首选.

I'm trying to make a basic app on Google App Engine with two modules using Google App Engine Modules(https://developers.google.com/appengine/docs/python/modules/) and They share session information between the modules:

Modules:

  • Module 1 - Login Page: a basic page with a login form where if is a valid user I create a session and then the user is redirected to the dashboard page(Module 2)
  • Module 2 - Dashboard Page: a page that show a message if the module can read the data in the session variable

The problem is that in the dashboard module the session data created in the Login Page(module 1) does not exist.

Is it possible access the sessions data between two o more modules in Google App Engine?

Source:

baseHandler.py

import webapp2
from webapp2_extras import sessions

class BaseHandler(webapp2.RequestHandler):

    def render_template(self, view_filename, params=None):
        params = {}
        path = os.path.join(os.path.dirname(__file__), 'views', view_filename)
        self.response.out.write(template.render(path, params))

    def display_message(self, message):
        """Utility function to display a template with a simple message."""
        params = {}
        self.render_template('message.html', params)

    def dispatch(self):
        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)

        try:
            # Dispatch the request.
            webapp2.RequestHandler.dispatch(self)
        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)

    @webapp2.cached_property
    def session(self):
        # Returns a session using the default cookie key.
        return self.session_store.get_session()

Module 1(Signin) main.py

from google.appengine.ext import ndb
import webapp2
from webapp2_extras.security import hash_password

import logging
import os
import sys
import jinja2

from src.basehandler import BaseHandler
from src.user import User

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape']
)

class MainPage(BaseHandler):

    def get(self):
        template_values = {}
        template = JINJA_ENVIRONMENT.get_template('templates/index.html')
        self.response.write( template.render( template_values ) )


    def post(self):
        email_address = self.request.get('input-email')
        password = self.request.get('input-password')

        password = hash_password( password, 'sha1', salt=None, pepper=None )

        qry = User.query(
            ndb.AND(User.email_address == email_address,
                    User.password == password
            )
        ).fetch()

        if qry:
            self.session['loggedin'] = True
            self.redirect('http://dashboard.myURL.appspot.com/')

        else:
            self.redirect('/?error=invaliduser')

config = {}
config['webapp2_extras.sessions'] = {
    'secret_key': 'my-super-secret-key',
}

app = webapp2.WSGIApplication([
    ('/', MainPage)
], debug=True, config=config )

Module 2(Dashboard) main.py

from google.appengine.ext import ndb
import webapp2

import logging
import os
import sys
import jinja2

from src.basehandler import BaseHandler
from src.user import User

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape']
)

class Main(BaseHandler):

    def get(self):
        msg = ''

        if not self.session.get('loggedin'):
            msg = 'There is not session'

        else:
            msg = 'There is a session'

        template_values = { 'msg': msg }
        template = JINJA_ENVIRONMENT.get_template('templates/index.html')
        self.response.write( template.render( template_values ) )

config = {}
config['webapp2_extras.sessions'] = {
    'secret_key': 'my-super-secret-key',
}

app = webapp2.WSGIApplication([
    ('/', Main)
], debug=True, config=config )

Any help is welcome, sorry if something is misspelled

解决方案

By default webapp2_extra.sessions uses cooki-based sessions. These will be tied to a specific domain. Your modules are probably at module1.yourapp.appspot.com and module2.yourapp.appspot.com (a guess). The second module won't be able to see the cookies set by the first module.

In your config try setting the domain for the cookie.

config['webapp2_extras.sessions'] = {
    'secret_key': 'my-super-secret-key',
     cookie_args': { 
         'domain' : "yourapp.appspot.com"
}

The docs say:

 - domain: Domain of the cookie. To work accross subdomains the
   domain must be set to the main domain with a preceding dot, e.g.,
   cookies set for `.mydomain.org` will work in `foo.mydomain.org` and
   `bar.mydomain.org`. Default is None, which means that cookies will
   only work for the current subdomain.

from: https://code.google.com/p/webapp-improved/source/browse/webapp2_extras/sessions.py

Or you could also use one of the other backends like memcache or datastore. This is preferred if your sessions contain sensitive info.

这篇关于如何在 Google App Engine Python 应用程序上的模块之间共享会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆