Web.py的优秀之处在于, 它没有过多的包装, 不会像其他web框架一样. 初次使用Web.py, 你可能会因为"闻到泥土的芬芳"而满心欢喜.
Web.py让你, 可以直接使用基本的Http methods, 这样, 我们就可以REST了.
下面我们描述如何实现一个用户管理的小系统, 当然, RESTly.
app.py:
- import web
- from user import User
- from utils import *
- urls = ('/User/(.*)', 'User')
- app = web.application(urls, globals())
- if __name__ == "__main__":
- app.run()
user.py:
- class User(object):
- def GET(self, name):
- #找到符合name的用户, 返回...
- @validate_key
- def POST(self, name):
- #根据post数据, 保存.
- @validate_key
- def DELETE(self, name):
- #删除user.
- def PUT(self, name=None):
- #新建一个对象.
用一个decorator来检查用户输入:
utils:py:
- import re
- VALID_KEY = re.compile('[a-zA-Z0-9_-]{1,255}')
- def validate_key(fn):
- #加上一些规则.
- pass
测试:
因为该死的浏览器们现在也不支持PUT, DELETE, 所以测试要费事一点.
还是用python:
- import httplib2
- h = httplib2.Http()
- h.request('http://localhost:8080/User/12345','POST','hello')
- h.request('http://localhost:8080/User/12345','GET')
- h.request('http://localhost:8080/User/12345','DELETE')
参考了:
http://jhcore.com/2008/09/20/getting-restful-with-webpy/