making regex capture group optional in url for a tornado app

avi

I want to make the regex capture group in a url optional. i.e. I want to handle both example.com/url and also example.com/url/something by a single handler.

I can use (r'/0(/?\w*)', Handler), but is that the right way to do it? If I go by this way, then I need to have a if-else block to see whether the requested url is /0 or /0/something.

Ideally, I would like something like this. (r'/0', r'/0/(\w+)' Handler). A handler which can accept two different url types and work on it. And in handler implementation, I would see if the parameter input to the handler is None, then I would display /0 page and consider user has submitted an answer otherwise.

Here is the reason why I want to do this. I am building a simple quiz app, where question will rendered by example.com/0 url and user will submit his answer as example.com/0/answer. I have 100 questions. In that case if I am handling questions and answers separately, then I would have 200 handlers against 100 handlers.

Or is this a bad design overall? Instead of creating 100 handlers, I have to use if-else blocks. Any suggestions?

PS: I don't want to change url formats. i.e. questions always will be displayed on example.com/0 (and not example.com/0/) and user will submit his answers as example.com/0/answer

Blender

I would just use HTTP methods and a single handler:

class QuestionHandler(RequestHandler):
    def get(self, id):
        # Display the question

    def post(self, id):
        # Validates the answer
        answer = self.get_argument('answer')

application = Application([
    (r'/(\d+)', QuestionHandler),
])

But if you insist on using a separate handlers:

class QuestionHandler(RequestHandler):
    def get(self, id):
        # Display the question

class AnswerHandler(RequestHandler):
    def post(self, id):
        # Validates the answer
        answer = self.get_argument('answer')

application = Application([
    (r'/(\d+)', QuestionHandler),
    (r'/(\d+)/answer', AnswerHandler),
])

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related