Google App Engine - 使用Python 2.7获取会话 [英] Google App Engine - Getting Sessions working with Python 2.7

查看:93
本文介绍了Google App Engine - 使用Python 2.7获取会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我对GAE是全新的,所以它可能会以错误的方式做到这一点 - 但我之前使用过PHP,会话是我保持持久数据的方式。我使用的是Python 2.7,因为这是我用于所有其他Python开发的东西 - 尽管我开始怀疑是否降级到2.5可能是一个有效的解决方案,如果不是理想的解决方案。

这个场景是我构建了一个概念验证站点,我需要一个虚拟登录按钮,它简单地设置一个名为'用户',其值为'admin'。然后,我想检查导航模板以查看是否设置了变量,如果有,我将添加一些额外的菜单命令。很简单。 (注:我知道这不是安全的,合理的或者应该做的任何事 - 问题是会话不工作,而不是我正在做的事 - 我正在做其他一些事情使用会话的代码 - 部署时都不工作)



GAE与Python有几个不同的会话库,我尝试了一个这是在Google搜索中最为推荐的 - gaeutilities ,但是这样做会导致错误,并且无法正常工作(我最终偶然发现这篇文章解释说它只是不兼容Python 2.7)。多一点搜索引导我去这个图书馆从我放入的appenginelearn.com,它完美的工作......直到我部署它 - 然后它什么都不做。我很想知道为什么这可能会失败。下面是我正在使用的相关代码:



我将utilng库目录从appenginelearn.com放入应用程序目录的根目录,然后导入Session: p>

  from util.sessions import Session 

然后我添加了Login和Logout类:

  class LogIn(webapp2.RequestHandler):
def get(self):
self.session = Session()
self.session ['user'] ='admin'
#将用户返回到他们登录的页面
referer = self.request.environ ['HTTP_REFERER'] \
如果self.request.environ中的'HTTP_REFERER'\
else'/'
self.redirect( referer)

类LogOut(webapp2.RequestHandler):
def get(self):
self.session = Session()
self.session.delete_item('用户')
self.redirect('/')

以及主类中的以下(可怕的)代码(这将在演示中的所有页面中完成)。

  class MainPage(webapp2.RequestHandler):
def get(self):
self.session = Session()
logging.info('Main page fired up')
如果'user'在self.session中:
user = self.session ['user']
else:
user = None

template_values = {
'user':user
}
template = jinja_environment.get_template('main.html')
self.response.out.write(template.render(template_values))

然后在HTML模板文件中

  {%if user%} 
< p>欢迎,{{user}}< / p>
{%endif%}

以及日志中的错误:

$ b / b

  2012-10-04 02:51:28.084 / login 302 143ms 0kb Mozilla / 5.0(Windows NT 6.1; WOW64)AppleWebKit / 537.4(KHTML,如Gecko)Chrome / 22.0.1229.79 Safari / 537.4 
* ip地址被删除* - - [04 / Oct / 2012:02:51:28 -0700]GET / login HTTP / 1.1302 136* site - 移除*Mozilla / 5.0(Windows NT 6.1; WOW64)AppleWebKit / 537.4(KHTML,与Gecko一样)Chrome / 22.0.1229.79 Safari / 537.4* site-removed *ms = 144 cpu_ms = 0 cpm_usd = 0.000015 instance = *实例已删除*
** I ** 2012-10-04 02:51:28.080
创建会话会话 - *删除会话编号*
** E ** 2012-10- 04 02:51:28.084
Set-Cookie:appengine-simple-session-sid = *删除会话号码*; Path = /


解决方案

你见过webapp2会话吗?它全部内置,您可以立即开始使用。



http://webapp-improved.appspot .com / api / webapp2_extras / sessions.html b
$ b


该模块为webapp2提供了一个轻量级但灵活的会话支持。
它有三个内置后端:安全cookie,memcache和数据存储。可以添加新的后端,扩展CustomBackendSessionFactory。
通过SessionStore.get_session()方法,会话存储可以使用不同的密钥提供多个会话,即使在同一个请求中使用不同的后端。默认情况下,它使用配置中的默认密钥返回会话。




  import webapp2 

从webapp2_extras导入会话
$ b $ class BaseHandler(webapp2.RequestHandler):
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()

#设置一个值:
self.session ['foo'] ='bar'

#获得一个值:
foo = self.session.get('foo')

然后围绕这个建立一个登录系统真的很容易,看起来你已经做到了。并且您首选使用带有webapp2会话的数据存储和/或memcache。

First of all, I'm brand new to GAE, so its possible I'm doing this the wrong way - but I've used PHP before and session was how I kept persistent data. I'm using Python 2.7 because that is what I use for all my other Python development - although I'm beginning to wonder if downgrading to 2.5 might be a valid solution, if not an ideal one.

The scenario is that I'm building a proof-of-concept site, and I need to have a 'dummy' login button that simply sets a session variable called 'user' with a value of 'admin'. I then want to check in the navigation template to see if the variable is set, and if so I'll add some extra menu commands. Very simple. (Note: I KNOW this isn't secure, sensible or anything that should be done - the problem is that session is not working, not what I'm doing with it - I'm doing a couple of other things in the code using session - none of them are working when deployed)

It seems there are a few different session libraries for GAE with Python and I tried the one that was most widely recommended in Google searches - gaeutilities, but this caused errors and wouldn't work (I eventually stumbled across this post to explain that its just not compatible with Python 2.7). A little more searching led me to this library from appenginelearn.com which I dropped in and it worked perfectly... until I deployed it - then it just does nothing. I'd love some pointers or advice as to why this might be failing. Here is the relevant code that I'm using:

I put the util library directory from appenginelearn.com in the root of the application directory, then imported Session:

from util.sessions import Session

Then I added the Login and Logout classes:

class LogIn(webapp2.RequestHandler):
    def get(self):
        self.session = Session()
        self.session['user'] = 'admin'
        # Return the user to the page they logged in from
        referer = self.request.environ['HTTP_REFERER'] \
                if 'HTTP_REFERER' in self.request.environ \
                else '/'
        self.redirect(referer)

class LogOut(webapp2.RequestHandler):
    def get(self):
        self.session = Session()
        self.session.delete_item('user')
        self.redirect('/')

And the following (awful) code in the main class (this will be done for all pages in the demo)

class MainPage(webapp2.RequestHandler):
    def get(self):
        self.session = Session()
        logging.info('Main page fired up')
        if 'user' in self.session:
            user = self.session['user']
        else:
            user = None

        template_values = {
            'user': user
            }
        template = jinja_environment.get_template('main.html')
        self.response.out.write(template.render(template_values))

And then this in the HTML template file

  {% if user %}
      <p>Welcome, {{user}}</p>
  {% endif %}

And the errors in the log:

2012-10-04 02:51:28.084 /login 302 143ms 0kb Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4
*ip address removed* - - [04/Oct/2012:02:51:28 -0700] "GET /login HTTP/1.1" 302 136 "*site-removed*" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4" "*site-removed*" ms=144 cpu_ms=0 cpm_usd=0.000015 instance=*instance removed*
**I** 2012-10-04 02:51:28.080
Creating session session-*session number removed*
**E** 2012-10-04 02:51:28.084
Set-Cookie: appengine-simple-session-sid=*session number removed*; Path=/

解决方案

Have you seen webapp2 sessions? It's all built in and you can get started right away.

http://webapp-improved.appspot.com/api/webapp2_extras/sessions.html

This module provides a lightweight but flexible session support for webapp2. It has three built-in backends: secure cookies, memcache and datastore. New backends can be added extending CustomBackendSessionFactory. The session store can provide multiple sessions using different keys, even using different backends in the same request, through the method SessionStore.get_session(). By default it returns a session using the default key from configuration.

import webapp2

from webapp2_extras import sessions

class BaseHandler(webapp2.RequestHandler):
    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()

# To set a value:
self.session['foo'] = 'bar'

# To get a value:
foo = self.session.get('foo')

Then it's real easy to build a login system around this, seems you've already done it already. And you get to use the datastore and/or memcache with the webapp2 sessions, as preferred.

这篇关于Google App Engine - 使用Python 2.7获取会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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