python tornado 样版 (包含出错页面)
2018-02-27 13:07:30
1 # -*- coding:utf-8 -*-
2
3 import tornado.web
4 import tornado.httpserver
5 import tornado.options
6 import tornado.ioloop
7
8 from tornado.options import define,options
9
10 define('port', default=8080, help='run port', type=int) # 定义端口
11 define('version', default='0.0.1', help='version 0.0.1', type=str) # 定义版本
12
13
14 class MainHandler(tornado.web.RequestHandler): # 定义路由
15
16 def get(self):
17 self.write('hello world ! <br>')
18 self.write('模版建立完成 <br>')
19
20
21 class NotFoundHandler(tornado.web.RequestHandler): # 若路由未匹配上,则跳转到出错页面
22
23 def get(self, *args, **kwargs): # 这里要发送404 否则会出现 405
24 self.send_error(404)
25
26 def write_error(self, status_code, **kwargs):# 重写错误页面
27 self.render('error.html') #会覆盖前面的 self.render('error.html')
28
29
30 application = tornado.web.Application(
31 handlers = [
32 (r"/",MainHandler),
33 (r"/(.*)", NotFoundHandler),
34 ],
35 template_path = 'error', # 指定路径
36 debug = True # 调试模式 文件修改后 自动重启服务器
37 )
38
39 if __name__ == '__main__':
40 print(options.port)
41 print(options.version)
42 tornado.options.parse_command_line()
43 # app = tornado.web.Application( handlers=[(r'/',MainHandler),] )
44 http_server = tornado.httpserver.HTTPServer(application)
45 http_server.listen(options.port) # 监听端口
46 tornado.ioloop.IOLoop.instance().start() #服务器自动循环 等待访问
目录结构
error.html
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>error</title>
6 <style>
7 *{
8 margin:0;
9 padding: 0;
10 }
11 div{
12 margin: auto;
13 margin-top: 60px;
14 width: 500px;
15 height: 30px;
16 text-align:center;
17 font-size: large;
18 font-weight: bold;
19 }
20 </style>
21 </head>
22 <body>
23
24 <div> 页面丢失啦 检查下路由</div>
25
26 </body>
27 </html>