基于twisted的web server框架简单原型

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


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值