第一个有意思的是RedirectHandler,它的代码和思路都比较有趣,代码很短,直接看:
class RedirectHandler(RequestHandler):
"""Redirects the client to the given URL for all GET requests.
You should provide the keyword argument "url" to the handler, e.g.::
application = web.Application([
(r"/oldpath", web.RedirectHandler, {"url": "/newpath"}),
])
"""
def initialize(self, url, permanent=True):
self._url = url
self._permanent = permanent
def get(self):
self.redirect(self._url, permanent=self._permanent)
StaticFileHandler:
其中最重要的是get方法,大致流程如下:
- 检查请求是否合法(映射后的文件地址是否正确)
- 设置header:
a. last-modified
b. content-type
c. Cache保存时间
d. 任何额外的header(通过调用set_extra_headers方法)
e. 根据request header中的“If-Modified-Since”,决定是否需要返回文件内容,或者简单返回304
f. 如果需要返回文件内容,计算并设置etag - 向buffer中写入(调用write方法)数据,并设置“Content-Length”
除此之外,还有一个有用的helper方法make_static_url,调用这个方法,会返回一个带有版本信息(v=???)的url
本来在web.py中还有几个比较重要的类UIModule和TemplateModule,不过简单看了一下基本没有明白到底在干毛,所以决定去看看template.py,之后回来再补上这两块内容。