Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle both GET and POST requests in TornadoWeb framework?

I'm really new to Python community, it's been a while that I'm trying to learn Flask and Tornado frameworks.

As you know we can handle GET and POST requests together in Flask very easily, For example a simple URL routing in Flask is something like this:

@app.route('/index', methods=['GET', 'POST'])
def index():
    pass

I googled and read Tornado documentation but I couldn't find a way to handle both GET and POST requests together in Tornado.

All I found is like code below:

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('intro.html')

    def post(self):
        self.render('intro.html')

Any idea how to do it in Tornado?

like image 1000
Ali Bahraminezhad Avatar asked Dec 16 '22 07:12

Ali Bahraminezhad


2 Answers

You can go with using prepare() method:

Called at the beginning of a request before get/post/etc. Override this method to perform common initialization regardless of the request method.

class MainHandler(tornado.web.RequestHandler):
    def prepare(self):
        self.render('intro.html')

Hope that helps.

like image 118
alecxe Avatar answered Apr 18 '23 03:04

alecxe


Ok.If you want to handle them together, try this

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.post()

    def post(self):
        self.render('intro.html')
like image 37
Srinivas Reddy Thatiparthy Avatar answered Apr 18 '23 05:04

Srinivas Reddy Thatiparthy