kivy Club

 找回密码
 注册
搜索
热搜: 活动 交友 discuz
查看: 6090|回复: 0

基于twisted应用http的简单例子

[复制链接]

2

主题

2

帖子

29

积分

新手上路

Rank: 1

积分
29
发表于 2016-5-9 11:49:04 | 显示全部楼层 |阅读模式
本帖最后由 dk1993 于 2016-5-9 11:50 编辑

#-*-coding:utf-8-*-

from kivy.support import install_twisted_reactor
install_twisted_reactor()


from twisted.protocols import basic
from twisted.internet import protocol,reactor
import re,json

class HttpEchoProtocol(basic.LineReceiver):
    def __init__(self):
        self.lines=[]
        self.gotRequest=False
    def lineReceived(self,line):
        self.lines.append(line)
        if not line and not self.gotRequest:
            self.sendResponse()
            self.gotRequest=True
    def sendResponse(self):
        params = self.lines[0].split(" ")[1]
        if params not in ["/","/?"]:
            dict_params = dict()
            if params == '/':
                self.factory.app.handle_message(dict_params)
            else:
                match = re.compile(r'(\w+)=(\w+)')
                nowparams = match.findall(params)

                for key,value in nowparams:
                    dict_params[key] = value
                self.factory.app.handle_message(dict_params)
        responseBody= json.dumps(dict_params)
        self.sendLine("HTTP/1.0 200 OK")
        self.sendLine("Content-Type: application/json")
        self.sendLine("Content-Length: %i"%len(responseBody))
        self.sendLine("")
        self.transport.write(responseBody)

class EchoFactory(protocol.ServerFactory):
    protocol = HttpEchoProtocol

    def __init__(self, app):
        self.app = app


from kivy.app import App
from kivy.uix.label import Label


class TwistedServerApp(App):
    def build(self):
        self.label = Label(text="server started\n")
        reactor.listenTCP(8005, EchoFactory(self))
        return self.label

    def handle_message(self, msg):
        print msg



if __name__ == '__main__':
    TwistedServerApp().run()


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|kivy.Club

GMT+8, 2024-4-20 01:15 , Processed in 0.046670 second(s), 22 queries .

Powered by Discuz! X3.2

Design By S!|ƽ̶

快速回复 返回顶部 返回列表