### 普通cookie
# 设置cookie
class PcookieHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
self.set_cookie(name="name", value="shao")
self.write("pcookie")
# 得到cookie
class GetcookieHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
cookie = self.get_cookie("name")
print(cookie)
self.write(cookie)
# 不会马上删除浏览器上的cookie,而是给它设置为空,并改变有效期,真正删除是浏览器做的
class ClearcookieHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
# 清除一个cookie
self.clear_cookie("name")
# 清除所有cookie
# self.clear_all_cookies()
self.write("clear")
普通cookie:
“key”=“value”
### 安全cookie
class ScookieHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
self.set_secure_cookie(name="name1", value="yuan")
self.write("安全cookie")
class GetscookieHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
scookie = self.get_secure_cookie("name1")
print(scookie)
self.write(scookie)
安全cookie:
“2|1:0|10:1545117975|5:name1|8:eXVhbg==|538ede9022397062bb9711a5476ad72dac37fb907dcf2feaac134af424062f0f”
# cookie计数
class CookienumHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
count = self.get_cookie("count", None)
if count:
count = int(count)
count += 1
else:
count = 1
self.set_cookie("count", str(count))
self.render("cookienum.html", count=count)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>home2</title>
</head>
<body>
<h1>home2主页</h1>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>登录</h1>
<form action="{{url}}" method="post">
{% module xsrf_form_html() %}
姓名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
# 用户登录
class LoginHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
# 获取next参数
next = self.get_argument("next", "/")
# print(next)
# 拼接url
url = "login?next=" + next
# 返回登录页面
self.render("login.html", url=url)
# 因为前面返回到登录页面,带入了url中有next参数,所以可以实现从哪里来回哪里去
def post(self, *args, **kwargs):
# 获取参数
name = self.get_argument("username")
pwd = self.get_argument("password")
# 如果信息正确
if name == "1":
# 获取next参数
next_url = self.get_argument(name="next", default="/")
# print(next_url)
# 重定向拼接的url
self.redirect(next_url + "?flag=logined")
else:
# 还是来到这个登录页面,带由原来的next值
next_url = self.get_argument(name="next", default="/")
self.redirect("/login?next=" + next_url)
class Home2Handler(tornado.web.RequestHandler):
# 重写get_current_user方法
def get_current_user(self):
# 判断是否登录
flag = self.get_argument("flag", None)
# 如果没登录就重定向到配置中的"login_url": "/login"
return flag
# 如果登录就调用下面的get方法
@tornado.web.authenticated
def get(self, *args, **kwargs):
self.render("home2.html")
# 开启xsrf保护
# 在模板中加{% module xsrf_form_html()%}
"xsrf_cookie": True,
"login_url": "/login"