how to set a cookie in tornado in python

To set a cookie in Tornado, you can use the set_cookie() method of the RequestHandler class. Here's an example:

main.py
import tornado.web

class MyHandler(tornado.web.RequestHandler):
    def get(self):
        # set the cookie
        self.set_cookie("my_cookie", "cookie_value")
        self.write("Cookie set!")
196 chars
8 lines

The set_cookie() method takes two arguments: the name of the cookie and its value. You can also pass additional parameters to customize the cookie, such as an expiration time:

main.py
import datetime
import tornado.web

class MyHandler(tornado.web.RequestHandler):
    def get(self):
        # set the cookie to expire in one hour
        expires = datetime.datetime.now() + datetime.timedelta(hours=1)
        self.set_cookie("my_cookie", "cookie_value", expires=expires)
        self.write("Cookie set!")
323 chars
10 lines

In this example, the expires parameter is set to one hour from now using the datetime module.

Note that when you set a cookie in Tornado, it is automatically sent as a Set-Cookie header in the HTTP response.

gistlibby LogSnag