2.6 redirect
:请求重定向
2.6.1 重定向到百度
访问index首页的时候,在浏览器地址栏输入127.0.0.1:8080/ (此时的端口号默认是定义的8080)有一个302的跳转,跳转到百度
2.6.2 重定向到自身
将重定向到百度注释,修改为
self.redirect('/temp/?name=cxk') #重定向到temp
这个是重定向的时候由参数,所以需要带上参数
在浏览器地址栏中输入url: 127.0.0.1:8080/temp/?name=cxk
会调用class RenderHandler
页面上会返回class RenderHandler中的内容
2.7 Cookie
get_cookie
/ set_cookie
/ clear_cookie
/ clear_all_cookies
:操作Cookie。
文件链接
链接:https://pan.baidu.com/s/14UGTSWgP_XeY6IUjbU6GXA
提取码:yn1w
3 登陆
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>首页</h3>
{% if username %}
{{ username }} 欢迎您
{% else %}
<a href="{{ reverse_url('login') }}">去登陆</a>
{% end %}
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>登录</h3>
<form action="" method="post">
姓名:<input type="text" name="username"> <br>
密码: <input type="password" name="password"> <br>
<input type="submit" value="登录"> <br>
</form>
</body>
</html>
manager .py
import os
import tornado.web
import tornado.ioloop
from tornado.web import url
class IndexHandler(tornado.web.RequestHandler):
def get(self):
username = self.get_cookie('username')
self.render('index.html', username=username)
class LoginHandler(tornado.web.RequestHandler):
def get(self):
self.render('login.html')
def post(self):
username = self.get_body_argument('username')
password = self.get_body_argument('password')
print(type(username), password)
if username == 'wqf' and password == '123456':
self.set_cookie('username', username, expires_days=7)
#self.set_cookie('token', 'token', expires_days=7)
self.redirect(self.reverse_url('index'))
else:
self.write('登录失败')
def make_app():
return tornado.web.Application(handlers=[
url(r'/index/', IndexHandler, name='index'),
url(r'/login/', LoginHandler, name='login'),
],
template_path = os.path.join(os.path.dirname(__file__), 'templates'),
static_path= os.path.join(os.path.dirname(__file__), 'static'),
)
if __name__ == '__main__':
app = make_app()
app.listen(8080)
tornado.ioloop.IOLoop.current().start()
文件链接
链接:https://pan.baidu.com/s/1l2Cirk_dHUMOZMORcA8s3A
提取码:x3yp