Bottle实例Todo-List—在数据库中插入一条记录

来源:互联网 发布:外卖消费人群数据分析 编辑:程序博客网 时间:2024/05/29 14:38

代码如下:

 Python Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# -*- coding:  utf-8 -*-
#!/usr/bin/python
# filename:insetList.py
# codedtime: 2014-8-26 22:52:29

import sqlite3
import bottle

@bottle.route('/new', method='GET')
def new_item():

    new = bottle.request.GET.get('task''').strip()

    conn = sqlite3.connect('todo.db')
    c = conn.cursor()

    c.execute("INSERT INTO todo (task,status) VALUES (?,?)", (new,1))
    new_id = c.lastrowid

    conn.commit()
    c.close()

    return '<p>The new task was inserted into the database, the ID is %s</p>' % new_id

bottle.debug(True)
bottle.run(host='127.0.0.1', port=8080, reloader = True)
在浏览器中输入:http://127.0.0.1:8080/new

输出结果:


说明插入了一条记录,其ID为5。


下面是使用模板(template)对本程序的扩展,代码如下:

 Python Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@bottle.route('/new2', method='GET')
def new_item():

    if bottle.request.GET.get('save','').strip():

        new = bottle.request.GET.get('task''').strip()
        conn = sqlite3.connect('todo.db')
        c = conn.cursor()

        c.execute("INSERT INTO todo (task,status) VALUES (?,?)", (new,0))
        new_id = c.lastrowid

        conn.commit()
        c.close()

        return '<p>The new task was inserted into the database, the ID is %s</p>' % new_id
    else:
        return bottle.template('new_task.tpl')
new_task.tpl模板如下:

1
2
3
4
5
<p>Add a new task to the ToDo list:</p>
<form action="/new2" method="GET">
<input type="text" size="100" maxlength="100" name="task">
<input type="submit" name="save" value="save">
</form>

在浏览器中输入:http://127.0.0.1:8080/new2

得到如下结果:


输入内容如:Hello,Johnny,how are you!!!  点击:save 则插入一条记录,其浏览器会显示:


表明插入数据成功。



0 0
原创粉丝点击