Archive for 七月, 2010

Pylons 入门实例教程 – cookie 和 session

By admin - Last updated: 星期六, 七月 3, 2010

本篇讲述在 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, [...]

Pylons 入门实例教程 – 数据库操作

By admin - Last updated: 星期四, 七月 1, 2010

前面两篇入门,讲述了 Pylons 大致开发的流程、表单以及文件上传,思路大致跟传统的开发类似。本篇简单讲述下在 Pylons 如何使用数据库。 本篇侧重点是使用 ORM 框架 SQLAlchemy。现在 Python 社区里关注度比较高的大概有三:SQLAlchemy、SQLObject 和 Storm。其实本人最早是研究了一下 Storm,后来听虾哥(@marchliu)在应用里不是很爽之,遂关注了下他推荐的 SQLAlchemy。当然,你也可以对应数据库的 DB-API 库来进行操作。 示例代码的数据库是 PostgreSQL,对应的 Python 库使用的是 psycopg2。至于 Pg 配置和使用这里不再累赘,请狗之。 Debian/Ubuntu 安装很简单: sudo aptitude install python-psycopg2 建立一个测试数据库,比如 test: smallfish@debian:~/workspace/python/hello$ su postgres postgres@debian:/home/smallfish/workspace/python/hello$ createdb -O smallfish test postgres@debian:/home/smallfish/workspace/python/hello$ exit smallfish@debian:~/workspace/python/hello$ psql -h 127.0.0.1 -p 5432 -U smallfish test 用户 smallfish 的口令: psql (8.4.4) [...]