Search code examples
pythontornado

Iterating all Values of self.request.arguments


Is there an easy way to access all of the values from a post in tornado without having to specify the argument for each one? At the moment just printing them to screen.

I can iterate through RequestHandler.request.arguments like this:

for f in self.request.arguments:
        details += "<hr/>" + f

And I can return an individual value like:

RequestHandler.get_argument("ArgumentName", default=None, strip=False)

But how do I dynamically return all of the values sent through a form?

Do I have to call get_argument for each one like this?

    for f in self.request.arguments:
        details += "<hr/>" + self.get_argument(f, default=None, strip=False)

This is what the RequestHandler looks like at the moment:

class Sent(tornado.web.RequestHandler):
    def post(self):
        details = ""
        for f in self.request.arguments:
            details += "<hr/>" + self.get_argument(f, default=None, strip=False)
        self.write(details)

Solution

  • arguments it's actually a dictionary (and that's why iterating over it gives you only its keys) so you can use values() method:

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    import textwrap
    import tornado.httpserver
    import tornado.ioloop
    import tornado.options
    import tornado.web
    
    from tornado.options import define, options
    define("port", default=8000, help="run on the given port", type=int)
    
    class TestHandler(tornado.web.RequestHandler):
        def post(self):
            details = ""
            for f in self.request.arguments.values():
                details += "<hr/>" + ", ".join(f)
            self.write(details)
    
    if __name__ == "__main__":
        tornado.options.parse_command_line()
    
        app = tornado.web.Application(handlers=[(r"/", TestHandler)])
        http_server = tornado.httpserver.HTTPServer(app)
        http_server.listen(options.port)
        tornado.ioloop.IOLoop.instance().start()
    

    I also use join() method because values of that dictionary are lists.