以下是一个使用 Tornado 搭建的简单 Web 应用案例,实现了一个基本的待办事项列表应用:
项目结构
tornado-todo-app/
├── main.py
├── templates/
│ ├── base.html
│ ├── index.html
│ └── item.html
└── static/
└── css/
└── style.css
代码说明
main.py
这是 Tornado 应用的主文件,负责定义路由、启动服务器和处理请求.
import tornado.ioloop
import tornado.web
import tornado.options
from tornado.options import define, options
define("port", default=8888, help="run on the given port", type=int)
class MainHandler(tornado.web.RequestHandler):
def get(self):
items = self.application.settings['items']
self.render("index.html", items=items)
class NewItemHandler(tornado.web.RequestHandler):
def post(self):
item = self.get_argument("item")
self.application.settings['items'].append(item)
self.redirect("/")
class DeleteItemHandler(tornado.web.RequestHandler):
def post(self):
item = self.get_argument("item")
self.application.settings['items'].remove(item)
self.redirect("/")
def make_app():
return tornado.web.Application(
[
(r"/", MainHandler),
(r"/new", NewItemHandler),
(r"/delete", DeleteItemHandler),
],
template_path="templates",
static_path="static",
items=[],
)
def main():
tornado.options.parse_command_line()
app = make_app()
app.listen(options.port)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
main()
templates/base.html
这是基础模板文件,用于定义页面的基本结构.
<!DOCTYPE html>
<html>
<head>
<title>待办事项列表</title>
<link rel="stylesheet" href="{{ static_url('css/style.css') }}">
</head>
<body>
<div class="container">
{% block content %}{% endblock %}
</div>
</body>
</html>
templates/index.html
这是主页面模板,用于显示待办事项列表和添加待办事项的表单.
{% extends 'base.html' %}
{% block content %}
<h1>待办事项列表</h1>
<form action="/new" method="post">
<input type="text" name="item" placeholder="添加待办事项" required>
<button type="submit">添加</button>
</form>
<ul>
{% for item in items %}
<li>{{ item }} <form action="/delete" method="post" style="display:inline;">
<input type="hidden" name="item" value="{{ item }}">
<button type="submit">删除</button>
</form></li>
{% endfor %}
</ul>
{% endblock %}
static/css/style.css
这是样式文件,用于美化页面.
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f4f4f4;
}
.container {
max-width: 600px;
margin: auto;
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
}
form {
margin-bottom: 20px;
}
input[type="text"] {
width: calc(100% - 22px);
padding: 10px;
margin-right: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
padding: 10px 20px;
background-color: #007BFF;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
ul {
list-style: none;
padding: 0;
}
li {
padding: 10px;
border-bottom: 1px solid #ddd;
}
li:last-child {
border-bottom: none;
}
运行项目
-
确保你已经安装了 Tornado. 如果还没有安装,可以使用以下命令安装:
pip install tornado
-
将上述代码保存到相应的文件中,确保文件结构正确.
-
在终端中,导航到项目目录并运行
main.py
:python main.py
-
打开浏览器,访问
http://localhost:8888/
,即可看到待办事项列表应用.
这个示例展示了如何使用 Tornado 创建一个简单的 Web 应用,你可以根据需要扩展功能和样式.