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

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

问题描述

我正在尝试使用Google App Engine模块在两个模块上制作基于Google App Engine的应用程序( https://developers.google.com/appengine/docs/python/modules/ )和他们共享模块之间的会话信息:



模块:




  • 模块1 - 登录页面:具有登录表单的基本页面,其中if是有效用户我创建会话,然后用户被重定向到仪表板页面(模块2)

  • 模块2 - 仪表板页面:显示消息,如果模块可以读取会话变量中的数据



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



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

来源:



baseHandler.py
$ b

  import webapp2 
from webapp2_extras导入会话
$ b $ class BaseHandler(webapp2.RequestHandler):
$ b $ 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))
$ b $ def display_message(self,message):
用简单的消息显示一个模板的实用函数。
params = {}
self .render_template('message.html',params)

def dispatch(self):
#获取此请求的会话存储。
self.session_store = sessions.get_store(request = self.request)

try:
#发送请求。
webapp2.RequestHandler.dispatch(self)
finally:
#保存所有会话。
self.session_store.save_sessions(self.response)

@ webapp2.cached_property
def session(self):
#使用默认的cookie关键字返回一个会话。
返回self.session_store.get_session()

模块1(登录)main .py

  from google.appengine.ext import ndb 
从webapp2_extras导入webapp2
.security import hash_password

导入日志记录
导入os
导入sys
导入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.g et('input-password')

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

qry = User.query(
ndb.AND(User.email_address == email_address,
User.password ==密码

).fetch()

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

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

config = {}
config ['webapp2_extras.sessions'] = {$ b $'secret_key':'my-super- (b $'b'',MainPage'
',debug = True,config = config),'
'

app = webapp2.WSGIApplication

第2单元(仪表板)main.py

  from google.appengine.ext import ndb 
导入webapp2

导入日志记录
导入操作系统
导入sys
从src.basehandler导入jinja2

从src.user导入BaseHandler
导入用户

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


class Main(BaseHandler):

def get(self):
msg =''

如果不是self.session.get('loggedin'):
msg ='There不是会话'

else:
msg ='有会话'

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 )

任何帮助都是值得欢迎的,如果拼写有误,抱歉

解决方案

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



在您的配置中,请尝试设置cookie的域名。

  config ['webapp2_extras.sessions'] = {
'secret_key':'我的超级密钥',
cookie_args':{
'domain':yourapp.appspot.com
}

文档说:


   -  domain:Cookie的域。要跨子域工作,必须将
域设置为带有前面点的主域,例如,为.mydomain.org设置的
Cookie将在`foo.mydomain.org`和$ b中工作$ b`bar.mydomain.org`。缺省值为None,这意味着cookie
仅适用于当前子域。


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

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


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天全站免登陆