manage.py
from tornado.ioloop import IOLoop # 处理I/O
from tornado.web import RequestHandler # 处理请求
from tornado.web import Application # 实例化APP网页
USER_DICT = {
'1': {'name': '金超', 'age': '22'},
'2': {'name': '小可', 'age': '42'},
'3': {'name': '小鱼', 'age': '32'},
'4': {'name': '小狗', 'age': '52'},
}
# 中间件用于验证是否登录
class AuthHandler(object):
def prepare(self):
# name = self.get_cookie('xxxxx') #与Django方法做对比
name = self.get_secure_cookie('xxxxx')
if not name:
self.redirect('/login')
# home页面 要先继承AuthHandler
class HomeHandler(AuthHandler, RequestHandler):
def get(self, *args, **kwargs):
self.render('index.html', user_dict=USER_DICT, num=[11, 22, 33])
# index主页面
class IndexHandler(AuthHandler, RequestHandler):
def get(self, *args, **kwargs):
# 用user_dict带入参数传给页面
self.render('index.html', user_dict=USER_DICT, num=[11, 22, 33])
# login登录页面函数
class LoginHandler(RequestHandler):
def get(self, *args, **kwargs):
self.render('login.html', error='')
def post(self, *args, **kwargs):
# Tornado和Django做类比
# self.get_query_argument('user') request.GET.get('user')
# self.get_query_arguments('user') request.GET.getlist('user')
# self.get_body_argument('user') request.POST.get('user')
# self.get_body_arguments('user') request.POST.getlist('user')
user = self.get_body_argument('user')
pwd = self.get_body_argument('pwd')
if user == 'alex' and pwd == '123':
self.set_secure_cookie('xxxxx', user)
self.redirect('/index')
return
self.render('login.html', error='用户名或密码错误')
# 在settings中注册templates和中间件cookie
settings = {
'template_path': 'templates',
'cookie_secret': 'asq3wurasldf'
}
# 在Application()方法里面写页面对应着函数
application = Application([
('/login', LoginHandler),
('/index', IndexHandler),
('/home', HomeHandler),
], **settings)
# listen()方法可以监控端口和IP默认是本机
if __name__ == '__main__':
application.listen(8888)
IOLoop.instance().start()
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户列表</h1>
<table>
<thead>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
</thead>
<thead>
<!--提取后端字典数据-->
{% for k,v in user_dict.items() %}
<tr>
<td>{{k}}</td>
<td>{{v['name']}}</td>
<td>{{v.get('age')}}</td>
</tr>
{% end %}
</thead>
</table>
<ul>
<!--提取后端列表-->
{% for item in num %}
<li>{{item}}</li>
{% end %}
</ul>
<h2>{{num[1]}}</h2>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post">
<input type="text" name="user">
<input type="text" name="pwd">
<input type="submit" value="提交">
<spon style="color: red">{{error}}</spon>
</form>
</body>
</html>