twisted08-1 多级访问-httpserver

来源:互联网 发布:gx8.86编程软怎么安装 编辑:程序博客网 时间:2024/06/06 00:29
#coding=utf8from twisted.internet import reactorfrom twisted.web.server import Sitefrom twisted.web.resource import Resource, NoResourcefrom twisted.web.static import Filefrom calendar import calendarimport sysclass Calendar(Resource):def __init__(self, year):#必须要调用父类的构造函数,否则由于#self.children没有初始化,getChildWithDefault会出错,因为self.children是NoneResource.__init__(self)#super在这里不能使用,super只能用于python新类(从object派生),不能用于老类#super(Calendar,self).__init__()assert(isinstance(year, (int, long)))self.year = yeardef 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->',namereturn Calendar(int(name))else:return NoResource()class URL_Dispatcher(Resource):def getChild(self, name, request):#name不是URI,仅是名称,request.uri才是真正的URIif name == '/' or not name:return self#return ico resouceelif 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->:',namey = 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()

0 0
原创粉丝点击