Search code examples
pythonposttornado

POST query in Tornado with multiple parameters


Code:

class Telegram(tornado.web.RequestHandler):
    def my_f(self,number):
        return number


    def get(self,number):
        self.write( self.my_f(number))

application = tornado.web.Application([
    (r"/number/(.*?)", Telegram),
    ])

Using this piece of code, i can trigger Telegram, providing it with something from the (.*?) part.

Question is: i need to make POST queries like: /number/messenger=telegram&phone=3332223332211

so that I can grab messenger parameter and phone parameter, and trigger the right class with provided phone number (like Telegram with 3332223332211)


Solution

  • POST requests (usually) have a body, so if you want everything in the URL you probably want a GET instead of a POST.

    The normal way to pass arguments is by form-encoding them. That starts with a ? and looks like this: /number?messenger=telegram&phone=12345. To use arguments like this in Tornado, you use self.get_argument("messenger") instead of an argument to the get() method.

    A second way of passing parameters is to put them in the "path" part of the URL, without a question mark. This is when you use (.*?) in your routing pattern and an argument to get(). Use this when you want to avoid the question mark for some reason (usually aesthetics).

    You can also combine the two: pass the messenger parameter in the URL as you've done here, and add ?number=12345 and use get_argument. But unless you really care about what your URLs look like, I recommend the first form.