Tornado同步api和异步api混写一例
生活随笔
收集整理的這篇文章主要介紹了
Tornado同步api和异步api混写一例
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
代碼如下:
import tornado.ioloop import tornado.web from tornado.httpclient import HTTPClient, AsyncHTTPClientfrom io import BytesIO import gzip import requests class MainHandler(tornado.web.RequestHandler):# 同步def get(self):res = requests.get("http://mobilecdnbj.kugou.com/api/v3/tag/list?pid=0&apiver=2&plat=0",stream=True)print("-------------------------------------------------")print(dir(res))buff = BytesIO(res.raw.read())f = gzip.GzipFile(fileobj=buff)res = f.read().decode('utf-8')print(res)self.write(res)class TestHandler(tornado.web.RequestHandler):# 異步async def get(self):http_client = AsyncHTTPClient()try:res = await http_client.fetch("http://www.baidu.com")except Exception as e:print("Error: %s" % e)else:passself.write("Hello, world1")settings = dict( debug=True )def make_app():return tornado.web.Application([(r"/", MainHandler),(r"/test", TestHandler),],**settings)if __name__ == "__main__":app = make_app()app.listen(8888)tornado.ioloop.IOLoop.current().start()運(yùn)行方法:
python test.py
?
同步API測(cè)試:
瀏覽器打開(kāi)127.0.0.1:8888/
?
異步API測(cè)試:
瀏覽器打開(kāi)127.0.0.1:8888/test
?
總結(jié)
以上是生活随笔為你收集整理的Tornado同步api和异步api混写一例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 股票回购是什么意思,为什么要回购?
- 下一篇: Tornado的同步API写法举例实现G