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

时间:2017-01-09 00:46:58

标签: python cherrypy

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

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

其次,我返回会话数据:

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

但是现在,我想将这些数据存储在变量中并返回它:

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

这样做时,我得到一个500内部:KeyError'变量'

1 个答案:

答案 0 :(得分:2)

不要忘记在配置中打开会话。它默认是禁用的。此外,您使用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函数

点击&#39; getter&#39;链接。浏览器显示:

您之前设置的电子邮件是email@email.com

瞧!这就是你在CherryPy中使用会话的方法。我希望这个例子可以帮助你。