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" />
姓:<input type="text" name="sname" value="$surName" />
<input type="submit" value="提交" />
</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" 模板文件
计划下面研究模板系统... |