如何将 cherrypy.session() 存储在变量中?

How to store cherrypy.session() in a variable?

首先,我在会话中存储了一封电子邮件:

@cherrypy.expose
def setter(self):
email = "email@email.com"
cherrypy.session["email"] = email
return "Variable passed to session" // This works fine!       

其次,我return会话数据:

@cherrypy.expose
def getter(self):
return cherrypy.session("email") // This works fine too! 

但是现在,我想将这些数据存储在一个变量中,return 它:

@cherrypy.expose
def getter(self):
variable = cherrypy.session("email")
return variable

执行此操作时,我收到 500 Internal: KeyError 'variable'

不要忘记在配置中打开会话。默认情况下它是禁用的。此外,您将 cherrypy.session 用作字典,它不是您调用的函数。

拿这个例子代码:

# rimoldi.py

import cherrypy

class TestApp:

    @cherrypy.expose
    def setter(self):
        email = "email@email.com"
        cherrypy.session["email"] = email
        return 'Variable stored in session object. Now check out the <a href="/getter">getter function</a>'

    @cherrypy.expose
    def getter(self):
        return "The email you set earlier, was " + cherrypy.session.get("email")

if __name__ == '__main__':
    cherrypy.quickstart(TestApp(), "/", {
        "/": {
            "tools.sessions.on": True,
            }
        })

你运行上面的例子有:

python rimoldi.py

CherryPy 说:

[09/Jan/2017:16:34:32] ENGINE Serving on http://127.0.0.1:8080
[09/Jan/2017:16:34:32] ENGINE Bus STARTED

现在将浏览器指向 http://127.0.0.1:8080/setter,您将看到:

变量存储在会话对象中。现在检查 getter 函数

单击 'getter' link。浏览器显示:

你之前设置的邮箱是email@email.com

瞧!这就是您在 CherryPy 中使用会话的方式。希望这个例子对你有帮助。