本篇讲述在 Pylons 里使用 cookie 和 session。

示例还是在上篇《Pylons 入门实例教程 – 数据库操作》的代码里继续添加。先来尝试下  cookie,添加新的 cookietest controller。

修改 index 方法,添加显示部分:

    def index(self):
        name = 'NULL'
        if request.cookies.has_key('name'):
            name = request.cookies['name']
        return 'cookie name=%s' % name

cookie 读取可以通过 request.cookies 对象,类似一个字典结构。需要注意的是读取时候用最好 has_key 判断下,这样避免抛 KeyError 异常。当然你也可以 try…catch 捕获一下。

再重新写一个方法,用来写 cookie。

    def writecookie(self):
        response.set_cookie("name", "smallfish")
        return "write cookie ok"

这里只是简单设置一个值得,set_cookie 还有其他参数,具体如下:

set_cookie(self, key, value='', max_age=None, path='/', domain=None, secure=None,
                 httponly=False, version=None, comment=None, expires=None, overwrite=False)

基本一般需要设置:max_age,path,domain,expires 这几个参数。

下面再来尝试一下 session:

smallfish@debian:~/workspace/python/hellodb$ paster controller sessiontest
Creating /home/smallfish/workspace/python/hellodb/hellodb/controllers/sessiontest.py
Creating /home/smallfish/workspace/python/hellodb/hellodb/tests/functional/test_sessiontest.py

和上面 cookie 例子类似,在 controller 里有两个方法,index 负责显示 session,writesession 负责写。

    def index(self):
        name = session.get('name', 'NULL')
        return 'session name=%s' % name

    def writesession(self):
        session['name'] = 'smallfish'
        session.save()
        return "save session ok"

index 方法里 get 后面的 NULL 是默认值。writesession 里需要注意下设置 session 之后需要 save。

删除 session 可以尝试如下:

del session['name']
# 删除所有
session.delete()

到这里,WEB 常用的一些东西在 Pylons 里基本走了一圈,包含 URL、模板、数据库和会话部分。

下一节将会涉及怎么在 Nginx 上发布 Pylons 应用。

Tagged with:  

5 Responses to Pylons 入门实例教程 – cookie 和 session

  1. dosou 说:

    顶鱼哥。不懂技术的我飘过

  2. jiaion 说:

    顶一下smallfish_xy 听seek老大说在这里能找到你希望能加下我Gtalk : [email protected] 或者QQ279425006 想和你请教一些python的问题.. 谢谢

  3. 婚礼 说:

    基本不用py写web,写底层还是比较好

  4. 白发先生 说:

    写得不错,你说的下节“在Nginx 上发布 Pylons 应用”怎么还没出来啊。

smallfish 发表评论 取消回复

电子邮件地址不会被公开。 必填项已被标记为 *

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

iBlog by PageLines

WP SlimStat