Tornado同步api和异步api混写一例

代码如下:

import tornado.ioloop
import tornado.web
from tornado.httpclient import HTTPClient, AsyncHTTPClient
 
from 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:
            pass
        self.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()

运行方法:

python test.py

同步API测试:

浏览器打开127.0.0.1:8888/

异步API测试:

浏览器打开127.0.0.1:8888/test

发布了824 篇原创文章 · 获赞 394 · 访问量 175万+

猜你喜欢

转载自blog.csdn.net/appleyuchi/article/details/105417975