使用Bottle框架构建ToDo应用:从入门到实践

使用Bottle框架构建ToDo应用:从入门到实践

bottle bottle.py is a fast and simple micro-framework for python web-applications. bottle 项目地址: https://gitcode.com/gh_mirrors/bo/bottle

前言

Bottle是一个轻量级的Python Web框架,它以简洁高效著称,非常适合快速开发小型Web应用。本文将带领读者通过构建一个完整的ToDo应用,深入理解Bottle框架的核心概念和使用方法。

环境准备

Python版本要求

Bottle支持广泛的Python版本,但本教程推荐使用Python 3.10或更高版本,因为我们会使用Python 3.10引入的match语句特性。如果使用Python 3.8或3.9,可以将match语句替换为if-elif-else结构。

安装Bottle

建议在虚拟环境中安装Bottle,以避免与其他项目产生依赖冲突:

python -m venv bottle_venv
source bottle_venv/bin/activate  # Linux/MacOS
.\Scripts\activate  # Windows
pip install bottle

数据库准备

本教程使用SQLite作为数据库,Python标准库已包含sqlite3模块,无需额外安装。首先创建数据库和示例数据:

import sqlite3
connection = sqlite3.connect('todo.db')
cursor = connection.cursor()
cursor.execute("CREATE TABLE todo (id INTEGER PRIMARY KEY, task char(100) NOT NULL, status bool NOT NULL)")
cursor.execute("INSERT INTO todo (task,status) VALUES ('Read the Python tutorial',0)")
cursor.execute("INSERT INTO todo (task,status) VALUES ('Visit the Python website',1)")
cursor.execute("INSERT INTO todo (task,status) VALUES ('Test various editors',1)")
cursor.execute("INSERT INTO todo (task,status) VALUES ('Choose your favorite WSGI-Framework',0)")
connection.commit()

Bottle基础概念

路由(Route)机制

Bottle的核心概念之一是路由,它将URL路径映射到Python函数。当用户访问特定URL时,Bottle会执行对应的函数并返回结果。

第一个Bottle应用

下面是一个简单的"Hello World"示例:

from bottle import Bottle

app = Bottle()

@app.route('/')
def index():
    return 'Hello from Bottle'

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8080)

运行后访问http://127.0.0.1:8080/即可看到结果。

构建ToDo应用

显示待办事项

首先实现显示所有未完成待办事项的功能:

import sqlite3
from bottle import Bottle, template

app = Bottle()

@app.route('/todo')
def todo_list():
    with sqlite3.connect('todo.db') as connection:
        cursor = connection.cursor()
        cursor.execute("SELECT id, task FROM todo WHERE status=1")
        result = cursor.fetchall()
        return template('show_tasks', rows=result)

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8080, debug=True, reloader=True)

使用模板美化输出

创建views/show_tasks.tpl模板文件:

<p>待办事项列表:</p>
<table border="1">
%for id, task in rows:
  <tr>
    <td>{{id}}</td>
    <td>{{task}}</td>
  </tr>
%end
</table>

开发辅助功能

在开发阶段,可以启用调试和自动重载功能:

app.run(debug=True, reloader=True)
  • debug=True:显示详细错误信息
  • reloader=True:代码修改后自动重载应用

扩展功能实现

添加新任务

from bottle import request

@app.route('/new', method='GET')
def new_item():
    return template('new_task')

@app.route('/new', method='POST')
def save_item():
    task = request.forms.get('task')
    with sqlite3.connect('todo.db') as conn:
        conn.execute("INSERT INTO todo (task, status) VALUES (?, 1)", (task,))
    return "任务已添加"

编辑任务

@app.route('/edit/<id:int>', method='GET')
def edit_item(id):
    with sqlite3.connect('todo.db') as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT task FROM todo WHERE id=?", (id,))
        task = cursor.fetchone()[0]
    return template('edit_task', id=id, task=task)

@app.route('/edit/<id:int>', method='POST')
def update_item(id):
    task = request.forms.get('task')
    with sqlite3.connect('todo.db') as conn:
        conn.execute("UPDATE todo SET task=? WHERE id=?", (task, id))
    return "任务已更新"

JSON API接口

from bottle import response
import json

@app.route('/as_json/<id:int>')
def show_json(id):
    response.content_type = 'application/json'
    with sqlite3.connect('todo.db') as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT id, task, status FROM todo WHERE id=?", (id,))
        data = dict(zip(['id', 'task', 'status'], cursor.fetchone()))
    return json.dumps(data)

生产环境部署

开发完成后,可以使用WSGI服务器如Waitress部署应用:

from waitress import serve
serve(app, host='0.0.0.0', port=8080)

总结

通过本教程,我们完成了以下功能:

  1. 显示待办事项列表
  2. 添加新任务
  3. 编辑现有任务
  4. 提供JSON格式API
  5. 实现生产环境部署

Bottle框架简洁高效,非常适合小型Web应用的快速开发。掌握了这些基础知识后,你可以进一步探索Bottle的更多高级特性,如插件系统、中间件等。

bottle bottle.py is a fast and simple micro-framework for python web-applications. bottle 项目地址: https://gitcode.com/gh_mirrors/bo/bottle

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

柳霆烁Orlantha

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

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

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

打赏作者

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

抵扣说明:

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

余额充值