python代码简单模拟Java中的MVC设计
包括两个文件:
一、 mymvc.py
import tornado.ioloop import tornado.web #访问地址 http://127.0.0.1:9870/main?ywdm=06&num1=10&num2=200 class TestClassA: def sub(self,a,b): return a-b def add(self,a,b): return a+b def chen(self,a,b): return a*b class TestClassB: def sub(self,a,b): return a-b def add(self,a,b): return a+b def chen(self,a,b): return a*b sys_config={} sys_config["01"]=['mymvc','TestClassA','add'] sys_config["02"]=['mymvc','TestClassA','sub'] sys_config["03"]=['mymvc','TestClassA','chen'] sys_config["04"]=['mymvc','TestClassB','add'] sys_config["05"]=['mymvc','TestClassB','sub'] sys_config["06"]=['mymvc','TestClassB','chen'] class MainHandler(tornado.web.RequestHandler): def get(self): ywdm=self.get_argument('ywdm') num1=int(self.get_argument('num1').encode('utf-8')) num2=int(self.get_argument('num2').encode('utf-8')) message="hello !" print type(num2) if ywdm in sys_config: my_module_name=sys_config[ywdm][0] my_class_name=sys_config[ywdm][1] my_method_name=sys_config[ywdm][2] my_module = __import__(my_module_name) my_class = getattr(my_module,my_class_name) my_obj = my_class() my_method = getattr(my_obj,my_method_name) ret=my_method(num1,num2) print "ret:",ret #message = "ret data:::"+ret message="ywdm:"+ywdm+"-data:"+str(ret) items = ["Item 1", "Item 2", "Item 3"] self.render("test.html", title="My title", items=items,config_items=sys_config) #self.write(message) #self.finish() application = tornado.web.Application([(r"/main", MainHandler),]) if __name__ == "__main__": application.listen(9870) tornado.ioloop.IOLoop.instance().start()
二、页面模板html: test.html
<html> <head> <title>{{ title }}</title> </head> <body> <ul> {% for item in items %} <li>{{ escape(item) }}</li> {% end %} </ul> <ul> {% for item in config_items %} <li>{{ escape(config_items[item][0]) }} -{{ escape(config_items[item][1]) }} -{{ escape(config_items[item][2]) }} </li> {% end %} </ul> </body> </html>
执行: mymvc.py
然后浏览器输入:http://127.0.0.1:9870/main?ywdm=06&num1=10&num2=200
返回如下:
- Item 1
- Item 2
- Item 3
- mymvc -TestClassA -sub
- mymvc -TestClassA -chen
- mymvc -TestClassA -add
- mymvc -TestClassB -chen
- mymvc -TestClassB -add
- mymvc -TestClassB -sub
时间: 2024-11-03 02:56:04