python bottle 实例教程:实现基于 SQLite 数据库的 Web 应用

houston 559 0

Python Bottle 实例教程:实现基于 SQLite 数据库的 Web 应用

在Python Web应用程序开发中,Bottle是一种微型Web框架,它是基于 Python 语言的轻量级Web框架,使用Bottle进行Web开发,使得在Python 中构建Web应用变得简单快速。此外,SQLite是一个嵌入式数据库管理系统,它是开源、轻量级、易部署的一个数据库,适用于小型的应用程序开发。本文将为您介绍如何实现一个基于SQLite数据库的Bottle Web 应用。

python bottle 实例教程:实现基于 SQLite 数据库的 Web 应用

1. 安装Bottle和SQLite

要将Bottle应用与 SQLite数据库集成,首先需要安装Bottle和SQLite。我们可以使用pip install命令在Python 中安装Bottle模块和SQLite库。

2. 创建数据库

在Python 中选择使用SQLite 做为数据库,可以使用sqlite3模块来连接数据库。下面是创建一个新的SQLite数据库和一个新表的SQL语句:

```

import sqlite3

conn = sqlite3.connect(mydb.db)

cursor = conn.cursor()

cursor.execute(CREATE TABLE student

(id INTEGER PRIMARY KEY AUTOINCREMENT,

name VARCHAR(20),

age SMALLINT,

class VARCHAR(20)))

conn.commit()

conn.close()

```

执行以上代码就可以创建一个名为mydb.db的SQLite数据库,同时也创建了一个名为student的表。

3. 初始化数据库的数据

可以使用Python代码插入初始数据:

```

import sqlite3

conn = sqlite3.connect(mydb.db)

cursor = conn.cursor()

cursor.execute(INSERT INTO student (name, age, class)

VALUES (Tom, 18, High School))

cursor.execute(INSERT INTO student (name, age, class)

VALUES (Jerry, 19, High School))

cursor.execute(INSERT INTO student (name, age, class)

VALUES (Tony, 21, University))

conn.commit()

print(Initial data has been inserted into database)

conn.close()

```

以上代码通过Python的sqlite3模块连接到mydb.db数据库,并向student表中插入了三个学生的数据。

4. 创建Bottle Web应用程序

在Python 中开发Bottle应用程序,需要新建一个.py文件来保存应用程序的代码,并使用Python所包含的Bottle模块。下面是一个简单的Python脚本,它是一个Bottle Web应用程序,通过Bottle来提供Web服务,并读取SQLite 数据库:

```

from bottle import route, run, template

import sqlite3

@route(/students)

def get_students():

conn = sqlite3.connect(mydb.db)

cursor = conn.cursor()

cursor.execute(SELECT * FROM student)

rows = cursor.fetchall()

conn.close()

return template(

% for row in rows:

% end

IDNameAgeClass
{{row[0]}}{{row[1]}}{{row[2]}}{{row[3]}}
, rows=rows)

if __name__ == __main__:

run(host=localhost, port=8080)

```

将上述代码保存为app.py文件,执行以下命令,就可以启动Bottle Web服务:

```

$ python app.py

```

现在可以在浏览器中访问http://localhost:8080/students页面,就可以看到学生信息的列表。

5. 自定义HTML模板

现在可以使用类似Bootstrap这样的UI库,设计所需的HTML模板,在Python 的Bottle应用中直接使用该模板。下面的HTML代码是使用Bootstrap的样式,设计了一个用户界面:

```

学生列表