web.py使用sqlite的待办事项列表无效的int()字面量
我在这里跟着教程学习 http://webpy.org/docs/0.3/tutorial,然后在网上查找如何用sqlite实现待办事项列表,找到了这个链接 http://kzar.co.uk/blog/view/web.py-tutorial-sqlite
我遇到了一个错误,怎么也解决不了。我搜索了很多,但找到的结果都没能帮到我。大多数建议是把括号里的引号去掉。
错误信息
<type 'exceptions.ValueError'> at /
invalid literal for int() with base 10: '19 02:39:09'
代码文件:code.py
import web
render = web.template.render('templates/')
db = web.database(dbn='sqlite', db='testdb')
urls = (
'/', 'index'
)
app = web.application(urls, globals())
class index:
def GET(self):
todos = db.select('todo')
return render.index(todos)
if __name__ == "__main__": app.run()
模板文件:templates/index.html
$def with (todos)
<ul>
$for todo in todos:
<li id="t$todo.id">$todo.title</li>
</ul>
数据库文件:testbd
CREATE TABLE todo (id integer primary key, title text, created date, done boolean default 'f');
CREATE TRIGGER insert_todo_created after insert on todo
begin
update todo set created = datetime('now')
where rowid = new.rowid;
end;
我对web.py和sqlite非常陌生
2 个回答
1
只需要把'created'这一列的类型改成时间戳(timestamp)就可以了:
日期的格式是"YYYY-MM-DD"(年-月-日)
而时间戳的格式是"YYYY-MM-DD HH:MM:SS"(年-月-日 时:分:秒)
这个SQL语句应该可以正常运行:
CREATE TABLE todo (id integer primary key, title text, created timestamp, done boolean default 'f');
CREATE TRIGGER insert_todo_created after insert on todo
begin
update todo set created = datetime('now', 'localtime')
where rowid = new.rowid;
end;
3
在某个地方,int()
函数被用来处理一个参数,内容是'19 02:39:09'
。但是,int()
函数无法处理冒号和空格。
>>> int('19 02:39:09')
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
int('19 02:39:09')
ValueError: invalid literal for int() with base 10: '19 02:39:09'
>>> int(':')
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
int(':')
ValueError: invalid literal for int() with base 10: ':'
>>> int('19 02 39 09')
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
int('19 02 39 09')
ValueError: invalid literal for int() with base 10: '19 02 39 09'
>>> int('19023909')
19023909
>>>
我建议使用replace()
函数来去掉这些空格和冒号,像这样做:
>>> date='19 02:39:09'
>>> date=date.replace(" ","")
>>> date
'1902:39:09'
>>> date=date.replace(":","")
>>> date
'19023909'
>>> int(date) ## It works now!
19023909
>>>
希望这能帮到你。