twisted08-1 多级访问-httpserver

#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()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值