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

代码如下:

 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 则插入一条记录,其浏览器会显示:


表明插入数据成功。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值