tornado 工作原理-监听方式-引入参数
重要函数
tornado.web.Application()
Application 是 tornado.web 框架的核心应用类.是与服务器对应的接口
里面保存了路由映射表,有一个 listen 方法用来创建一个 http 服务器的实例绑定了端口
IOLoop.current() 返回当前线程的IOLoop实例
IOLoop.start() 启动IOLoop实例的I/O循环,开启监听
三种监听方式
除了进程个数设置,三种方式效果一样,默认开启1个线程
- 最简洁的方式,单进程
app.listen(8888)
- 增加一个HttpServer对象,单进程
HttpServer = tornado.httpserver.HTTPServer(app)
httpServer.listen(8888)
- 推荐使用,可以设置多进程
HttpServer = tornado.httpserver.HTTPServer(app)
httpServer.bind(8888)
httpServer.start(5) # 默认开启1个线程
三种引入参数方法
这里引入的参数为端口号 port
- tornado.options.parse_command_line() 命令行输入
import tornado.web # web框架模块
import tornado.ioloop # 核心IO循环模块,封装了linux的epoll和BSD的kqueue,是tornado高效的基础
import tornado.options
tornado.options.define("port",default=8888,type=int)
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello Python!")
if __name__ == "__main__":
tornado.options.parse_command_line()
app = tornado.web.Application([(r"/", IndexHandler)])
app.listen(tornado.options.options.port)
tornado.ioloop.IOLoop.current().start()
2. tornado.options.parse_config_file(“config”) config配置文件
import tornado.options
import tornado.web # web框架模块
import tornado.ioloop # 核心IO循环模块,封装了linux的epoll和BSD的kqueue,是tornado高效的基础
tornado.options.define("port",default=8888, type=int)
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello Python!")
if __name__ == "__main__":
tornado.options.parse_config_file("config")
app = tornado.web.Application([(r"/", IndexHandler)])
app.listen(tornado.options.options.port)
tornado.ioloop.IOLoop.current().start()
- import config 方式
不使用 tornado 自带的options方式
import tornado.ioloop # 核心IO循环模块,封装了linux的epoll和BSD的kqueue,是tornado高效的基础
import config
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello Python!")
if __name__ == "__main__":
print(config.options["list"])
app = tornado.web.Application([(r"/", IndexHandler)])
app.listen(config.options["port"])
tornado.ioloop.IOLoop.current().start()