简体   繁体   中英

How to do url path check in prepare method of tornado RequestHandler?

I want to do path check in tornado like this:

class MyRequestHandler(tornado.web.RequestHandler):
    def initialize(self):
        self.supported_path = ['path_a', 'path_b', 'path_c']

    def get(self, action):
        if action not in self.supported_path:
            self.send_error(400)

    def post(self, action):
        if action not in self.supported_path:
            self.send_error(400)

    # not implemented
    #def prepare(self):
        # if action match the path 


app = tornado.web.Application([
    ('^/main/(P<action>[^\/]?)/', MyRequestHandler),])

How can I check it in prepare , not both get and post ?

How can I check it in prepare, not both get and post?

Easy!

class MyRequestHandler(tornado.web.RequestHandler):
    def initialize(self):
        self.supported_path = ['path_a', 'path_b', 'path_c']

    def prepare(self):
        action = self.request.path.split('/')[-1]
        if action not in self.supported_path:
            self.send_error(400)


    def get(self, action):
        #real code goes here

    def post(self, action):
        #real code goes here

Here we think, that your action does not contain '/' in it's name. In other cases check will be different. By the way, you have access to request in prepare method - that is enough.

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