How can I use Tornado and Redis asynchronously?

后端 未结 4 759
天涯浪人
天涯浪人 2021-02-04 07:31

I\'m trying to find how can I use Redis and Tornado asynchronously. I found the tornado-redis but I need more than just add a yield in the code.

I have the

4条回答
  •  天命终不由人
    2021-02-04 07:51

    For Python >= 3.3, I would advise you to use aioredis. I did not test the code below but it should be something like that:

    import redis
    import tornado.web
    from tornado.web import RequestHandler
    
    import aioredis
    import asyncio
    from aioredis.pubsub import Receiver
    
    
    class WaiterHandler(tornado.web.RequestHandler):
    
        @tornado.web.asynchronous
        def get(self):
            client = await aioredis.create_redis((host, 6279), encoding="utf-8", loop=IOLoop.instance().asyncio_loop)
    
            ch = redis.channels['test_channel']
            result = None
            while await ch.wait_message():
                item = await ch.get()
                if item['type'] == 'message':
                    print item['channel']
                    print item['data']
                    result = item['data']
    
            self.write(result)
            self.finish()
    
    
    class GetHandler(tornado.web.RequestHandler):
    
        def get(self):
            self.write("Hello world")
    
    
    application = tornado.web.Application([
        (r"/", GetHandler),
        (r"/wait", WaiterHandler),
    ])
    
    if __name__ == '__main__':
        print 'running'
        tornado.ioloop.IOLoop.configure('tornado.platform.asyncio.AsyncIOLoop')
        server = tornado.httpserver.HTTPServer(application)
        server.bind(8888)
        # zero means creating as many processes as there are cores.
        server.start(0)
        tornado.ioloop.IOLoop.instance().start()
    

提交回复
热议问题