import tornado.ioloop
import tornado.web
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("hello world")
class ASyncHandler(tornado.web.RequestHandler):
@
gen.coroutine
def get(self):
print("11111111111")
self.write("hello world -------")
class A2SyncHandler(tornado.web.RequestHandler):
@
gen.coroutine
def get(self):
http_client = AsyncHTTPClient()
print("777777777777")
# http_client.fetch 会进入阻塞的方法, 切换协程
# response = yield http_client.fetch("
https://asia.playstation.com/hk")
# res = response.body
# 放开下面一行注释, /async 必须等这里跑完才会跑, 也会有被阻塞的感觉
res = str(jies(600)) # 不会进入阻塞的方法, 线程可能一直被这个函数占用了,
# yield gen.sleep(10) 主动让出 10 秒执行权, 10 秒后回到这里执行
print("888888888888")
self.write(res)
application = tornado.web.Application([
(r"/", MainHandler),
(r"/async", ASyncHandler),
(r"/async2", A2SyncHandler)],
)
def jies(n):
for i in range(10**5):
x = 1
return n*jies(n-1) if n != 1 else 1
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()