简体   繁体   中英

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)

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 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM