Search code examples
pythonasync-awaittornado

how to use coroutine in tornado as a global initialize request handler


i want to use a base requestHander to get the global arguments from redis before all request(GET、POST..) ,and i use coroutine in tornado web as async&await. but i use aredis to client redis-server ,and the baseHandler doesn't support to use async in init method,because i need when the Class super the parent Class can get the arguments or the request have been confirm in check params from redis.
code like this.

import aredis
redis_client = aredis.StricRedis('redis://xxxx') 
class BaseHandler(tornado.web.requestHander):
    def check_request(self):
         check_one = await redis_client.get(self.request.body['param'])
         if not check_one:
             self.finish(dict(msg='refused'))
    async def get_params(self):
         data = await redis_client.get('xxx')
         self.data = data

class UserHander(BaseHander):
     async def get(self,*args,**kwargs):
         data = self.data
         return self.finish(data)

Solution

  • See the RequestHandler.prepare() method. You can create this method in your subclass and it will be called before every request method.

    Example:

    class BaseHandler(...):
        async def prepare(self):
           # your code here ...