初始tornado框架

2.7版本的一个简单的框架

 1 from wsgiref.simple_server import make_server
 2 
 3 def new():
 4     return 'new'
 5 def index():
 6     return 'index'
 7 
 8 urls={'/new':new,
 9       '/index':index
10       }
11 
12 def Runserver(environ,start_response):
13     start_response('200 OK',[('Content-Type','text/html')])
14     url=environ['PATH_INFO']
15     if url in urls.keys():
16         ret=urls[url]()
17     else:
18         ret='404'
19     return ret
20 
21 if __name__=="__main__":
22     httpd=make_server('',8000,Runserver)
23     httpd.serve_forever()
View Code

一个简单的tornado脚本

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import tornado.ioloop
 4 import tornado.web
 5 
 6 is_login=False
 7 
 8 class IndexHandler(tornado.web.RequestHandler):
 9     def get(self):
10         self.render('index.html')
11 
12 class LoginHandler(tornado.web.RequestHandler):
13     def get(self, *args, **kwargs):
14         self.render('login.html',status='')
15 
16     def post(self, *args, **kwargs):
17         username = self.get_argument('username',None)
18         password = self.get_argument('password',None)
19         if username == 'dalong' and password == "123":
20             self.set_cookie('auth', '1')
21             self.redirect('/manager')
22         else:
23             self.render('login.html',status='登陆失败')
24 class ManagerHandler(tornado.web.RequestHandler):
25     def get(self,*args, **kwargs):
26         co=self.get_cookie('auth')
27         print(co)
28         if co=='1':
29             self.render('manager.html')
30         else:
31             self.redirect('/login')
32 
33 class LogoutHandler(tornado.web.RequestHandler):
34     def get(self,*args, **kwargs):
35         self.set_cookie('auth','0')
36         self.redirect('/login')
37 
38 settings = {
39     'template_path': 'views', # 模板路径的配置
40 }
41 
42 # 路由映射,路由系统
43 application = tornado.web.Application([
44     # (r"/index", MainHandler),
45     (r"/index", IndexHandler),
46     (r"/login", LoginHandler),
47     (r"/manager", ManagerHandler),
48     (r"/logout", LogoutHandler),
49 ], **settings)
50 
51 if __name__ == "__main__":
52     # socket运行起来
53     application.listen(8888)
54     tornado.ioloop.IOLoop.instance().start()
View Code

 

posted @ 2016-07-25 16:48  很大的龙  阅读(151)  评论(0编辑  收藏  举报