python 之Twsited

Twisted是一个事件驱动的网络框架,其中包含了诸多功能,例如网络协议,线程,数据库管理,网络操作,电子邮件等

事件驱动

一,注册事件

二,触发事件

自定义事件框架  event_fram.py

复制代码
 1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 """
 4 @author: zengchunyun
 5 """
 6 event_list = []  # 定义一个事件驱动列表,只有注册了该事件列表的对象都会被该事件方法处理
 7 
 8 
 9 def run():
10     for event in event_list:
11         obj = event()
12         obj.execute()  # 注册该事件的对象必须自己实现这个方法
13 
14 
15 class BaseHandler(object):
16     """
17     用户必须继承该类,从而规范所有类的方法,(类似接口功能)
18     """
19     def execute(self):
20         raise Exception("you must overide execute method")
复制代码

调用事件驱动

复制代码
 1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 """
 4 @author: zengchunyun
 5 """
 6 import event_fram
 7 
 8 
 9 class MyHandler(event_fram.BaseHandler):
10     def execute(self):
11         print("event driver execute MyHandler")
12 
13 
14 event_fram.event_list.append(MyHandler)
15 event_fram.run()
复制代码

 

posted @ 2018-12-24 09:59  kiddy-x  阅读(144)  评论(0编辑  收藏  举报