#coding=utf8
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.resource import Resource, NoResource
from twisted.web.static import File
from calendar import calendar
import sys
class Calendar(Resource):
def __init__(self, year):
#必须要调用父类的构造函数,否则由于
#self.children没有初始化,getChildWithDefault会出错,因为self.children是None
Resource.__init__(self)
#super在这里不能使用,super只能用于python新类(从object派生),不能用于老类
#super(Calendar,self).__init__()
assert(isinstance(year, (int, long)))
self.year = year
def render_GET(self, request):
return '<html><h1><pre>%s</pre></h1></html>' % calendar(self.year)
def getChild(self, name,request):
if name.isdigit() and int(name) > 1990:
#递归处理下一个name的日历
print 'next_name->',name
return Calendar(int(name))
else:
return NoResource()
class URL_Dispatcher(Resource):
def getChild(self, name, request):
#name不是URI,仅是名称,request.uri才是真正的URI
if name == '/' or not name:
return self
#return ico resouce
elif name == 'favicon.ico':
return File('d:/down.png')
#仅仅只能处理 http://localhost:8000/1995
#不能处理http://localhost:8000/1995/1995 or http://localhost:8000/1995/1995/../../..
#如果返回一个资源对象,将继续getChild往下递归访问,以'/'为分隔符
elif name.isdigit() and int(name) > 1990:
print 'name->:',name
y = int(name)
return Calendar(y)
else:
return NoResource()
def render_GET(self, request):
return '<html><h1>Calendar</h1></html>'
if __name__ == '__main__':
reload(sys)
sys.setdefaultencoding('utf8')
s = Site(URL_Dispatcher())
reactor.listenTCP(8000,s)
reactor.run()
twisted08-1 多级访问-httpserver
最新推荐文章于 2024-07-12 17:01:23 发布