【4】项目结构+基本的Tornado服务
项目地址:
简单的tornado服务分支: simple
项目结构
创建对应的文件夹并测试一个最简单的功能
main.py
1 #!/usr/bin/env python 2 # coding:utf-8 3 4 import tornado.ioloop 5 import tornado.options 6 import tornado.httpserver 7 import tornado.web 8 from tornado.options import define, options 9 10 from url import url 11 from application import settings 12 13 define("port", default="7777", help="run on the given port", type=int) 14 15 16 class Application(tornado.web.Application): 17 18 def __init__(self): 19 tornado.web.Application.__init__(self, url, **settings) 20 21 if __name__ == '__main__': 22 tornado.options.parse_command_line() 23 http_server = tornado.httpserver.HTTPServer(Application()) 24 http_server.listen(options.port) 25 tornado.ioloop.IOLoop.instance().start()
url.py
1 #!/usr/bin/env python 2 # coding:utf-8 3 4 import tornado.web 5 import application 6 7 url = [(r"^/(favicon\.ico)", tornado.web.StaticFileHandler, 8 dict(path=application.settings['static_path']))] 9 url += [(r"^/", "handlers.index.IndexHandler")]
application.py
1 #!/usr/bin/env python 2 # coding:utf-8 3 4 import tornado.web 5 import os 6 7 8 # get cookie_secret 9 # import base64 10 # import uuid 11 # print base64.b64encode(uuid.uuid4().bytes+uuid.uuid4().bytes) 12 13 settings = dict( 14 template_path=os.path.join(os.path.dirname(__file__), "templates"), 15 static_path=os.path.join(os.path.dirname(__file__), "static"), 16 xsrf_cookies=True, 17 cookie_secret="RYxFqFQyRCiCZ/nxFfTMCrbqZpRZ5UW9tQ86fKvrfIw=", 18 login_url="/login", 19 debug=True, 20 )
index.py
1 #!/usr/bin/env python 2 #-*- coding:utf-8 -*- 3 4 import tornado.web 5 6 7 class IndexHandler(tornado.web.RequestHandler): 8 9 ''' 10 主页处理类 11 ''' 12 13 def get(self): 14 self.write("Index")
favicon.ico选择自己喜欢的ico放置于static目录下
这样,最简单的一个Web服务就完成了,Ctrl+B运行main.py
在浏览器输入localhost:7777,看到返回的Index字符串则表示运行正常。
更改说明:git仓库的默认端口为8909 -->在浏览器输入localhost:8909,看到返回的Index字符串则表示运行正常。