web.py 进阶例程

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

#!/usr/bin/python
import web

urls = (
        '/sample', 'sample',
        '/(.*)', 'hello'
       )

class hello:
    def GET(self, name):
        i = web.input(times=1)
        if not name: name = 'world'
        for c in xrange(int(i.times)): print 'Hello,', name+'!'

class sample:
    def _request(self):
        render = web.template.render('templates/')
        cache = False
        i = web.input(fname = 'yingbo', sname = 'qiu')
        #交换 fname, sname 的值
        firstName = i.sname
        surName = i.fname
        print render.sample(firstName, surName)
    def GET(self):
        self._request()
    def POST(self):
        self._request()

if __name__ == "__main__":
    import os
    os.environ['PHP_FCGI_CHILDREN'] = "1" #FastCGI 运行模式
    web.run(urls, globals())

模板:templates/sample.html

$def with (firstName, surName)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>dup2.net</title>
</head>
<body>
<form action="sample" method="post">
名:<input type="text" name="fname" value="$firstName" /><br />
姓:<input type="text" name="sname" value="$surName" /><br />
<p><input type="submit" value="提交" /></p>
</form>
</body>
</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" 模板文件

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

"class

"class login:"应该是"class sample:"吧.

os.environ['PHP_FCGI_CHILDREN'] = "1" #FastCGI 运行模式

跟PHP有什么关系呢?不解.~

的确是我弄错了...改

的确是我弄错了...改命名的时候漏了一处

另外的这个环境变量我是看代码知道的..

似乎起因是
a. PHP 启动 FastCGI 模式的时候需要这个参数
b. lighttpd 等 webserver 在启动 FastCGI 的时候通常会配置这个参数
c. web.py 框架判断读到这个环境变量的时候就进入 FastCGI 模式运行.

估计也可以在 apache 配置文件里面配 code.py 进入 fastcgi 模式,或者执行 code.py 之前配置运行的环境变量,而不是这样在程序里面主动写环境变量.

恩,python的确语法比pe

恩,python的确语法比perl规范多了,可惜俺当初先perl为主了
呵呵。perl适合懒惰的程序员用。