set_cookie(name, value, domain=None, expires=None, path='/', expires_days=None)
参数说明:
示例:
import tornado.web
import tornado.ioloop
import tornado.httpserver
import os
import pymysql
import time
from tornado.options import define, options
define("port", default=8001, help="run on the given port", type=int)
class IndexHandler(tornado.web.RequestHandler):
def get(self):
print(self.get_cookie("n1"))
print(self.get_cookie("n2"))
print(self.get_cookie("n3"))
print(self.get_cookie("n4"))
self.set_cookie("n1", "v1")
self.set_cookie("n2", "v2", path="/new", expires=time.strptime("2018-07-30 23:59:59", "%Y-%m-%d %H:%M:%S"))
self.set_cookie("n3", "v3", expires_days=20)
# 利用time.mktime将本地时间转换为UTC标准时间
self.set_cookie("n4", "v4", expires=time.mktime(time.strptime("2018-07-30 23:59:59", "%Y-%m-%d %H:%M:%S")))
self.write("OK")
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", IndexHandler),
(r"/new", IndexHandler),
]
settings = dict(
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "statics"),
debug=True,
)
super(Application, self).__init__(handlers, **settings)
if __name__ == "__main__":
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
get_cookie(name, default=None)
class IndexHandler(RequestHandler):
def get(self):
n3 = self.get_cookie("n3")
self.write(n3)
clear_cookie(name, path='/', domain=None):删除名为name,并同时匹配domain和path的cookie。
clear_all_cookies(path='/', domain=None):删除同时匹配domain和path的所有cookie。
class ClearOneCookieHandler(RequestHandler):
def get(self):
self.clear_cookie("n3")
self.write("OK")
class ClearAllCookieHandler(RequestHandler):
def get(self):
self.clear_all_cookies()
self.write("OK")
注意:执行清除cookie操作后,并不是立即删除了浏览器中的cookie,而是给cookie值置空,并改变其有效期使其失效。真正的删除cookie是由浏览器去清理的。