[파이썬] Tornado에서의 HTTPS 설정

HTTPS is an encrypted version of the HTTP protocol, ensuring secure communication between the server and the client. It is widely used to protect sensitive data such as passwords, credit card information, and personal details.

To enable HTTPS in Tornado, we need two essential components: a SSL certificate and a private key. These can be obtained from a certificate authority (CA) or generated locally for testing purposes.

Here’s an example code snippet demonstrating how to configure HTTPS in Tornado:

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.httpclient

from tornado.options import define, options

define("port", default=8888, help="run on the given port", type=int)
define("certfile", default="cert.pem", help="path to certificate file", type=str)
define("keyfile", default="key.pem", help="path to key file", type=str)

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

def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
    ])

if __name__ == "__main__":
    tornado.options.parse_command_line()
    
    ssl_options = {
        "certfile": options.certfile,
        "keyfile": options.keyfile,
    }

    app = make_app()
    server = tornado.httpserver.HTTPServer(app, ssl_options=ssl_options)
    server.listen(options.port)
    tornado.ioloop.IOLoop.current().start()

Let’s go through the code step by step:

  1. We import the necessary Tornado modules and define the command-line options for specifying the port, certificate file (cert.pem), and key file (key.pem).
  2. In this example, we create a handler class MainHandler that responds with a “Hello, HTTPS!” message.
  3. The make_app function defines our application by associating the handler with a specific route.
  4. In the if __name__ == "__main__": block, we parse the command-line options.
  5. Then, we define the SSL options using the provided certificate and key files.
  6. Next, we create the Tornado application and configure the HTTPServer to use the SSL options.
  7. Finally, we start the server on the specified port and enter the Tornado event loop.

To run the server, you would execute the following command in your terminal:

python your_file_name.py --port=443 --certfile=path/to/cert.pem --keyfile=path/to/key.pem

Make sure to replace your_file_name.py, path/to/cert.pem, and path/to/key.pem with the actual filenames and paths of your certificate and key files.

With this setup, your Tornado server will be accessible over HTTPS, providing a secure channel for communication with clients.

Remember, when deploying to production, it’s recommended to obtain an SSL certificate from a trusted CA to ensure the highest level of security.