# -*- coding=utf-8 -*-
import sys, os
from twisted.web import server, resource
from twisted.internet import reactor
from twisted.web import static, server
from twisted.web.client import Request
import json
webroot = ''
class PathHandler(object):
# 处理 http://domain/user/xxx 格式的请求
path_root = '/user/'
def __init__(self):
pass
@classmethod
def handle(self, request, path, args):
index = path.find(self.path_root)
if index < 0:
return False
path = path[index+len(self.path_root):]
index = path.find('?')
if index > 0:
path = path[:index]
func = 'handle_' + str(path)
ret = False
args_ = {}
for key in args:
args_[key] = args[key][0]
if hasattr(PathHandler, func):
print('func--', func)
ret = {'errcode': 0, 'info': 'success'}
exec "ret=self." + func + '(args_, request, ret)'
else:
print('func %s not found'%(func))
return ret
@classmethod
def handle_get_user_info(self, args, ret):
"""
/user/get_user_info
handle_xxx:类似java web中spring的处理方式,函数自动对应到URI
这里的xxx对应get_user_info,请求路径为 /user/get_user_info
"""
pass
@classmethod
def handle_test404(self, args, request, ret):
"""
测试返回404错误
如果这里直接finish,那么需要返回1,见server.py L228: if body == NOT_DONE_YET: return
"""
request.setResponseCode(404)
ret = {'errcode': 1, 'info': 'not found'}
request.write(json.dumps(ret))
request.finish()
return 1
class WebSite(resource.Resource):
def __init__(self):
resource.Resource.__init__(self)
# self.putChild("*", self)
def getChild(self, path, request):
uri = request.uri
# 处理静态文件
if uri.endswith('.js') or uri.endswith('.html')\
or uri.endswith('.css') or uri.endswith('.png') \
or uri.endswith('.jpg') or uri.endswith('.jpeg') \
or uri.endswith('.ico') or uri.endswith('.gif') \
or uri.endswith('.txt') :
print webroot + uri
return static.File(webroot + uri)
return self
# 处理get请求
def render_GET(self, request):
uri = request.uri
print 'uri:', uri
try:
# 将请求交给PathHandler处理,进一步扩展:创建并注册任意的handler以处理各类请求
ret = PathHandler.handle(request, request.uri, request.args)
except Exception, e:
print e.message
ret = False
print 'ret:' + str(ret)
if ret == 1:
print('ret is None')
return ret
if not ret:
ret = {'errcode': 1, 'info': 'not implemented!'}
return json.dumps(ret) # 返回json格式
# 处理post请求
def render_POST(self, request):
return self.render_GET(request)
def run():
dirpath = os.getcwd()
global webroot
webroot = dirpath + '/../../webroot'
reactor.listenTCP(8081, server.Site(WebSite()))
reactor.run()
if __name__ == '__main__':
run()
基于twisted的web server框架简单原型
最新推荐文章于 2024-10-10 09:21:09 发布