美文网首页
同步异步api

同步异步api

作者: 月夜星空下 | 来源:发表于2021-08-07 15:15 被阅读0次
    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")
                print(res)
            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(4444)
        tornado.ioloop.IOLoop.current().start()
    

    相关文章

      网友评论

          本文标题:同步异步api

          本文链接:https://www.haomeiwen.com/subject/jgfgvltx.html