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

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

问题描述

首先,我是 GAE 的新手,所以我可能以错误的方式做这件事 - 但我之前使用过 PHP,会话是我保存持久数据的方式.我正在使用 Python 2.7,因为这是我用于所有其他 Python 开发的内容——尽管我开始怀疑降级到 2.5 是否可能是一个有效的解决方案,如果不是一个理想的解决方案.

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.

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

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)

似乎有几个不同的 GAE 会话库和 Python,我尝试了在 Google 搜索中最广泛推荐的一个 - gaeutilities,但这会导致错误并且无法工作(我最终偶然发现了 这篇文章 解释它只是与 Python 2.7 不兼容).更多的搜索让我找到了这个图书馆来自 appenginelearn.com,我加入了它,它运行良好......直到我部署它 - 然后它什么都不做.我希望得到一些关于为什么这可能会失败的指示或建议.这是我正在使用的相关代码:

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:

我将appenginelearn.com中的util库目录放在应用目录的根目录下,然后导入Session:

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))

然后这个在 HTML 模板文件中

And then this in the HTML template file

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

以及日志中的错误:

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=/

推荐答案

你见过 webapp2 会话吗?这一切都是内置的,您可以立即开始使用.

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

https://webapp2.readthedocs.io/en/latest/api/webapp2_extras/sessions.html

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

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')

那么围绕这个构建一个登录系统真的很容易,看来你已经做到了.您可以根据需要将数据存储和/或内存缓存与 webapp2 会话一起使用.

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