[파이썬] Tornado의 RequestHandler

Tornado is a powerful web framework for building asynchronous web applications in Python. One of the key components in Tornado is the RequestHandler class, which handles incoming HTTP requests and generates HTTP responses.

Getting Started

To use the RequestHandler class, you need to create a subclass and override its methods to define the desired behavior.

Here’s an example of a basic RequestHandler class:

import tornado.web

class MyRequestHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, Tornado!")

# Creating the Tornado application and specifying the routes
app = tornado.web.Application([
    (r"/", MyRequestHandler),
])

# Starting the Tornado server
if __name__ == "__main__":
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

In the above code, we define a subclass MyRequestHandler that inherits from tornado.web.RequestHandler. We override the get method to handle the incoming GET requests to the URL endpoint “/”. Inside the get method, we call the write method to send the response body to the client.

The tornado.web.Application class is used to create the Tornado application and specify the routes. In this example, we map the URL pattern “/” to the MyRequestHandler class.

Finally, we start the Tornado server by calling the listen method and passing the desired port number. The IOLoop.current().start() method starts the server and keeps it running until the process is terminated.

RequestHandler Methods

The RequestHandler class provides various methods that can be overridden to handle different types of HTTP requests:

For example, to handle a POST request, you can override the post method in your RequestHandler subclass:

class MyRequestHandler(tornado.web.RequestHandler):
    def post(self):
        # Handle the POST request here

Request and Response Handling

Inside the RequestHandler subclass, you have access to various attributes and methods for handling requests and generating responses.

Conclusion

In this blog post, we introduced the RequestHandler class in Tornado and showed how to create a basic web application using Tornado. We also explored how to handle different types of requests and generate responses. Tornado’s RequestHandler provides a powerful and flexible way to handle incoming HTTP requests in Python applications.