当前位置

技术

技术

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: 

更新了 DV-2-XviD 以及 Python IrDA Socket extension

DV-2-XviD 更新到 0.8.2 版本. 其中一个 bug 是刚开始学 Python 开发的时候,使用了全局变量在函数间传递信息,结果上一次运行的结果影响了下一轮调用。还是那个指出 0.8 的 bug 的用户又发现了 0.8.1 的 bug.

Python IrDA Socket 则是编译了 Win32 2.5 环境下的扩展

Topic: 

web.py 进阶例程

web.py 的首页提供了一个 13 行的例子来演示如何开始一个应用,但其网站上似乎就没有别的更进一步的例子了。这两天简短学习了一下,写一个进阶例程。包括:读取 GET/POST 变量,以及模板的使用。

  1. #!/usr/bin/python
  2. import web
  3.  
  4. urls = (
  5.         '/sample', 'sample',
  6.         '/(.*)', 'hello'
  7.        )
  8.  
  9. class hello:
  10.     def GET(self, name):
  11.         i = web.input(times=1)
  12.         if not name: name = 'world'
  13.         for c in xrange(int(i.times)): print 'Hello,', name+'!'
  14.  
  15. class sample:
  16.     def _request(self):
  17.         render = web.template.render('templates/')
  18.         cache = False
  19.         i = web.input(fname = 'yingbo', sname = 'qiu')
  20.         #交换 fname, sname 的值
  21.         firstName = i.sname
  22.         surName = i.fname
  23.         print render.sample(firstName, surName)
  24.     def GET(self):
  25.         self._request()
  26.     def POST(self):
  27.         self._request()
  28.  
  29. if __name__ == "__main__":
  30.     import os
  31.     os.environ['PHP_FCGI_CHILDREN'] = "1" #FastCGI 运行模式
  32.     web.run(urls, globals())

模板:templates/sample.html

  1. $def with (firstName, surName)
  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  4. "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  5. <html>
  6. <head>
  7. <meta">http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  8. <html>
  9. <head>
  10. <meta</a> http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  11. <title>dup2.net</title>
  12. </head>
  13. <body>
  14. <form action="sample" method="post">
  15. 名:<input type="text" name="fname" value="$firstName" /><br />
  16. 姓:<input type="text" name="sname" value="$surName" /><br />
  17. <p><input type="submit" value="提交" /></p>
  18. </form>
  19. </body>
  20. </html>

访问 http://www.dup2.net/papp/sample 就可以看到效果。这个 sample 可以接受 GET/POST 请求。参数为 fname 和 sname。执行结果就是将这两个值交换显示。

web.py 每个 URL 请求分发到一个类。这里就把 sample 分发给 sample 类,其它的所有 URL 分发给 hello 类。访问一下 http://www.dup2.net/papp/ladf/badf?times=3 看看 hello 的效果。

HTTP GET 和 POST 分别执行 class 里面的 method。使用 web.input() 来取得 request 参数和值。

然后用 web.template.render() 初始化模板目录。方法名 "sample" 对应的 "sample.html" 模板文件

计划下面研究模板系统...

Topic: 

Apache 2.2 + web.py + RoR

刘韧的 1234 文体

1. mod_python 非常不主流,所有 Python 的 Web 框架都内置一个 HTTP Server 的实现(在 Python 世界里这样做太简单了),web.py 还包括了 FastCGI/SCGI 的支持。RoR 也同样通过 mongrel 提供了 web server 支撑。

2. lighttpd 支持反向代理,也支持 FastCGI,再加上它确实够轻,性能也不错,而且用 apache httpd 不够酷,于是它成了新潮 web hacker 们的最爱。

3. 其实我很有理由使用 lighttpd,因为我的内存只有 128M。但我想通过 http 端口来跑 svn,没办法,只有用 apache。编译的时候加上 rewrite/proxy 的支持

./configure --prefix=/usr/local/apache2  --enable-so -enable-ssl \
   --enable-rewrite --enable-proxy --enable-proxy-http

mod_fcgid 的编译过程也很简单,直接 make; make install 就好了。
注意:fcgid 的配置为 SetHandler fcgid-script 而不是 fastcgi-script

4. 我下载的是 web.py 0.2,但网站上的关于如何运行在 Apache FastCGI 模式下的说明是错误的(怀疑说的还是 0.1 版本的方法)。我的方法是增加了这么两行

import os
os.environ['PHP_FCGI_CHILDREN'] = "1"

注意:必须安装 flup 包,web.py 才能支持 FastCGI。

最后的配置为

  1.     <Directory "/usr/local/apache2/htdocs/papp">
  2.         Options ExecCGI
  3.         AllowOverride None
  4.         Order allow,deny
  5.         Allow from all
  6.         <Files code.py>
  7.             SetHandler fcgid-script
  8.         </Files>
  9.         Options +FollowSymLinks
  10.         <IfModule mod_rewrite.c>
  11.             RewriteEngine on
  12.             RewriteBase /papp/
  13.             RewriteCond %{REQUEST_URI} !^/icons
  14.             RewriteCond %{REQUEST_URI} !^/favicon.ico$
  15.             RewriteCond %{REQUEST_URI} !^(/.*)+code.py/
  16.             RewriteRule ^(.*)$ code.py/$1 [PT]
  17.         </IfModule>
  18.     </Directory>

code.py 放在 htdocs 的 papp 目录下

5. RoR 的 mongrel 起在 8000 端口,我在 htdocs 下创建了一个 rapp 目录,然后配置 rewrite

  1.     <Directory "/usr/local/apache2/htdocs/rapp">
  2.         <IfModule mod_rewrite.c>
  3.             RewriteEngine on
  4.             RewriteBase /rapp/
  5.             RewriteRule ^(.*) <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a>$1 [P]
  6.         </IfModule>
  7.     </Directory>

有的网站上的配置是 ProxyPass 什么什么的,我的这个重写到本地端口的配置方法是从 karrigell 那里学来的,觉得也挺好的

Topic: 

jabberd2 2.1 release

很早就订阅了 jabberd2 的邮件列表,似乎开发不是很活跃。有次和其中一个开发人员 gtalk,他说目前也有不过 3 个开发者,而且其中一个对现有的框架不满意,觉得很难去 scalable,要另起炉灶,感觉这个项目前景不妙。。。不管怎么说,刚刚看到邮件列表里面的新消息,2.1 发布了!

http://ftp.xiaoka.com/jabberd2/releases/jabberd-2.1.tar.bz2
Release Note / New Features

- dropped SCOD, using CyrusSASL
- jabberd2 uses system expat library
- router level XMPP packet filtering
- modules/features ported and integrated:
* Linux epoll support
* full vcard-temp support
* storing user status in DB
* offline messages quotas and more robust handling
* Advanced Message Processing (AMP)
* authreg_pam realm handling
- RFC3921 compliance (presence handling)
- dropped legacy features (presence-invisible)
- certificate handling fixes (not complete yet)
- proper SRV records handling
- c2s HTTP connection forwarding to real HTTP server
- other im servers on the router are not listed on disco
- using route errors for stanza errors
- only PostgreSQL is now fully supported
(patches needed and welcome)
- numerous bug (crash, leaks) and stability fixes

Topic: 

ffdshow tryouts

今天总算搞明白 ffdshow 现在的状态了。原始开发者 milan_cutka 不知什么原因终止了对这个项目的维护,最后一次 build 是 20051129。接着 celtic_druid 大牛做了一段时间的 build (就是把各种各样的 patch 抓进来)。然后 videomixer9 在 sourceforge 上启动了这个新项目 ffdshow-tryouts,总共 4 名核心开发人员吧,一直都很活跃,可以说现在的 ffdshow-tryouts 已经取代了原来 ffdshow 的官方地位。

因为在各大搜索引擎搜索 ffdshow 返回的还是停止更新的那个项目,所以写篇文章说明一下。

Topic: 

DV-2-XviD 0.8.1

今天收到一封 DV-2-XviD 用户反馈来信(感叹一下:中国软件业的希望是争取国外用户啊...这是第二个老外给我报 bug 了),说是不支持 Scenalyzer Live 4.0 捕获的 AVI。查了查代码,应该是自己原来对 AVI 格式理解有误造成的,很快就改好了。

不过在生成 py2exe 的时候出了一些问题。因为前不久系统重装,所以 Python 也顺手换上了 2.5,结果就导致一系列扩展都要重新安装。先是 py2exe 0.6.5 报告 zlib 错误,google 之,是由于 Python 2.5 for Win32 内置 zlib 导致的,py2exe 暂时也没有正式发布的包解决这个故障,还有在邮件列表上找到一个 patch 搞定了。然后就是最新的 wxPython 2.7.2.0 在 py2exe 的时候依赖 gdiplus.dll,于是降级回 2.6.3.3,整个世界清净了。

其实新版本比老版本还少了一行脚本,但 Python 2.5 环境下转换出来的 DV-2-XviD.exe 整整大了 360k,郁闷...

Topic: 

梦想中的资源管理器——ExplorerXP

一两个月前,一哥们给我推荐了一个软件Total Commander,优点是可以在里面打开多个页显示文件文件夹,有了它就不用打开好几个资源管理器了。安装后,发现原来曾经见过一个台湾人用过这个东东。仔细尝试各种功能,调整设置,兴冲冲琢磨了一两个小时,刚开始很兴奋,可是后来发现它对目录树的处理非常不好,简直让我无法忍受。

IE7是支持多页的,我开始遐想,是不是vista里面的资源管理器就是左边一棵树,右边可以是多页的呢?前两天突然又想起这茬,vista不是有不少人试用过吗,看看别人是怎么说资源管理器的变化的?看了几个评测,没有发现新的资源管理器有这个功能。正当我沮丧的时候,看到搜索结果中有一个ExplorerXP,网页里的截图就是我希望的那样,把Groups的panel关掉,样子跟资源管理器就没什么区别了。oh yeah,这样就可以直接在2000和XP系统中用这个多页的资源管理器了。vista里面没有这个也好,反正我也用不起vista,免得看到眼馋。

它可以设置很多的快捷键,其中Ctrl+T,Ctrl+W是一定要设的,跟FxNotepad++一样;剪切、拷贝、粘贴设成连在一起的三个F*键也挺好;另外获得某个文件的路径、获得路径+文件名、只获得文件名这三个操作设上快捷键也很有用;Groups可以用来当做bookmarks用;[View]->[Folders]->[Make All as This Folder]把排列的版式变得一致。

Topic: 

Softpedia Editorial Team 发来的信!!


没想到已经决定暂时中止开发的程序居然获得了承认.

Hello,

Your product "DV-2-XviD 0.8" has been tested by the Softpedia labs and found to be
completely clean of adware/spyware components.

We are impressed with the quality of your product and encourage you to keep
this high standards in the future.

To assure our visitors that "DV-2-XviD 0.8" is clean, we have granted it with the
"100% FREE" Softpedia award. Moreover, to let your users know about this
certification, you may display this award on your website, on software boxes
or inside your product.

More information about your product's certification and the award is available
on this page: http://www.softpedia.com/progClean/DV-2-XviD-Clean-57206.html

Your product review page is located at:
http://www.softpedia.com/get/Multimedia/Video/Encoders-Converter-DIVX-Related/DV-2-XviD.shtml

Please feel free to link to us using the URL above.
If you choose to link to the award page for your product, you may use the
award graphic or a text link such as: "100% FREE award granted by Softpedia"

Don't hesitate to contact us for more information.

Sincerely,
       The Softpedia Team
Topic: 

用 libevent 实现一个简单的 http server

今天由于要查询 memcached 的使用,转到了 libevent,发现它大概一个月前发布了 1.2 版本,一个很重要的更新就是增加了对 http 协议的封装。

于是尝试自己写一个 http server,查看 manual 无迹可循。google 之,看到一个人写的 sample,而且他还写了其它一些的 libevent 的例程。强烈推荐学习。

嘻嘻,练好 google 大法很重要哦。用 google generate 代码的能力比 Visual Studio 的 wizard 强多了。以后写程序之前首先打开浏览器 search,然后 copy & paste 到编辑器里面去.... (YY 中)

最后要说的是,感觉用 libevent 来完成一个 http application server 似乎也是相当的可行呢。至少上手比 apache module 简单多了。比如 JEP/XEP-0124 , http binding. 传统上都是在 java 上实现的,现在我看到了 C 上实现的曙光。可惜最近业余实在没有精力去写什么程序了。

Topic: 
订阅 RSS - 技术