使用Bottle框架构建ToDo应用:从入门到实践
前言
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)
总结
通过本教程,我们完成了以下功能:
- 显示待办事项列表
- 添加新任务
- 编辑现有任务
- 提供JSON格式API
- 实现生产环境部署
Bottle框架简洁高效,非常适合小型Web应用的快速开发。掌握了这些基础知识后,你可以进一步探索Bottle的更多高级特性,如插件系统、中间件等。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考