第34课 python中用Tornado搭建web案例

以下是一个使用 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;
}

运行项目

  1. 确保你已经安装了 Tornado. 如果还没有安装,可以使用以下命令安装:

    pip install tornado
    
  2. 将上述代码保存到相应的文件中,确保文件结构正确.

  3. 在终端中,导航到项目目录并运行 main.py

    python main.py
    
  4. 打开浏览器,访问 http://localhost:8888/,即可看到待办事项列表应用.

这个示例展示了如何使用 Tornado 创建一个简单的 Web 应用,你可以根据需要扩展功能和样式.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

结伴同行~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值