当前位置

web.py 进阶2,连接 MySQL 数据库,以及其它的一些内容..

第一部分在这里

申明一点,这里的例子都是基于 web.py 0.2 版本的。现在网上的 web.py 中文教程是基于 0.1 的,如果你看到的文章一开始说要安装什么 Cheetah,那肯定不适用现在的情况了。

首先说的是 Python 连 MySQL,以及 UTF-8 字符集的事情。我这里假设你的应用是纯 UTF-8 的,而且使用 MySQL 4.1 以上的版本。

Python for MySQL 的连接扩展在 mysql-python,Debian Sarge 的包里面是 1.2.1c2 版,是不支持 4.1 的 Charset 特性的,最新的 1.2.1_p2 版支持的很好,只不过从这个版本开始必须依赖 Python2.4 了。

当使用 mysql-python connect()的时候有两个重要参数,charset,use_unicode。charset 就是指定连接以后 set names 的字符集;use_unicode 则指定 fetch result 的结果是用 'unicode string' or 'string' 类型 ? 由于最后输出的模板都是按照 string 来解析的,为了能正确运算,必须把这里设置成 0

web.py 类似 Java Servelet,可以在程序出错的时候抛出一大块异常;而且因为直接处理所有的 URL,所以它也内置一个自定义 url not found 的机制。

例子:首先是初始化部分的代码

  1. def mynotfound():
  2.     render = web.template.render('templates/')
  3.     print render._404()
  4.  
  5. web.webapi.internalerror = web.debugerror
  6. web.webapi.notfound = mynotfound
  7. if __name__ == "__main__":
  8.     import os
  9.     os.environ['PHP_FCGI_CHILDREN'] = "1" #FastCGI 运行模式
  10.     web.config.db_parameters = dict(dbn='mysql', user='webpy', pw='passwordofwebpy', \
  11.             host='localhost',port=3306,db='club',charset='utf8',\
  12.             use_unicode=0)
  13.     web.run(urls, globals())

上面定义了新的 404 处理函数以及用 web.debugerror 代替原来的 500 处理函数,debugerror 可以抛出一个非常漂亮的异常页面。在 __main__ 函数里面设定了 mysql 的连接参数,这里连接到一个叫 club 的数据库

增加一个对所有以 'sample/' 开头的 URL 分发类 samples

  1. urls = (
  2.         '/sample', 'sample',
  3.         '/sample/(.*)', 'samples',
  4.         '/(.*)', 'hello'
  5.        )
  6.  
  7. class samples:
  8.     GET = web.autodelegate('GET_')
  9.     POST = web.autodelegate('POST_')
  10.     def show_signup(self, users):
  11.         render = web.template.render('templates/sample/')
  12.         print render.signup(users)
  13.     def GET_signup(self):
  14.         users = web.select('user')
  15.         self.show_signup(users)
  16.     def POST_signup(self):
  17.         i = web.input()
  18.         web.insert('user',
  19.                 user_name=i.user_name,
  20.                 user_email=i.user_email,
  21.                 user_passport=i.user_passport)
  22.         users = web.select('user')
  23.         self.show_signup(users)

注意:这里用了 autodelegate ,来把 sample/abc 的 GET 方法转到 GET_abc 方法去处理

运行实例:

访问 http://www.dup2.net/papp/sample/notfound 可以看到我自定义的 _404 输出结果

访问 http://www.dup2.net/papp/sample/signup可以执行我这里访问 MySQL 的例子.

我这里的 email 是设置成 unique key 的,这样可以在这个页面提交表单内容里面把 email 赋值为已经存在的 email,比如 spam@notinput-realemail-here.org,哈,就可以看到一个很帅的异常了..

Topic: 

评论

看到个东西,http://www.cs.tut.fi/~ask/cinpy/ 就是 c in py,可以在 py 里直接嵌入 c 代码加快速度。不知道你看到这个东西没。一些应用里计算密集的部分可以用 C 写了。

http://code.google.com/p/ctcinline/
C Inline code inlining with python