我使用了一些非常简单的代码来创建一个带有peewee的数据库,我是使用python ORM的新手,所以我无法确定为什么我会收到一大堆错误。 这段代码的作用是:首先我创建一个数据库'diary.db' 使用的数据类型是条目(文本字段)和日期(DateTimeField)。我创建了一些函数:'initialize'来运行基本命令并初始化数据库,'menu_loop'将显示一个无限循环的菜单,并且可以调用函数'add_entry'来向数据库添加新条目。
下面是代码:
#!/usr/bin/env python3
from collections import OrderedDict
from peewee import *
import datetime
import sys
db = SqliteDatabase('diary.db')
class Diary(Model):
entries = TextField()
date = DateTimeField(default = datetime.datetime.now)
class Meta:
database = db
def initialize():
"""initializes the database"""
db.connect()
db.create_tables([Diary], safe = True)
#end of initialize
def menu_loop():
"""show menu"""
choice = 0
while choice != 2:
print("Enter '2' to quit")
print('1) to add an entry')
choice = input()
if choice == 1:
add_entry()
#end of menu_loop
def add_entry():
"""add an entry"""
print("Enter your entry, press ctrl+d when done")
data = sys.stdin.read().strip()
if data:
while(True):
option = input('\nSave entry?[1 = yes 0 = no] ')
if option == 1:
Diary.create(content=data)
print ("Saved sucessfully!")
if option == 0:
print ("Program exited")
break;
#end of add_entry
if __name__ == '__main__':
initialize()
menu_loop()
和错误日志
Enter '2' to quit
1) to add an entry
1
Enter your entry, press ctrl+d when done
this is my new entry
hello world^D
Save entry?[1 = yes 0 = no] 1
Traceback (most recent call last):
File "ispythonsmart.py", line 50, in <module>
menu_loop()
File "ispythonsmart.py", line 30, in menu_loop
add_entry()
File "ispythonsmart.py", line 41, in add_entry
Diary.create(content=data)
File "/Library/Python/2.7/site-packages/peewee.py", line 4494, in create
inst.save(force_insert=True)
File "/Library/Python/2.7/site-packages/peewee.py", line 4680, in save
pk_from_cursor = self.insert(**field_dict).execute()
File "/Library/Python/2.7/site-packages/peewee.py", line 3213, in execute
cursor = self._execute()
File "/Library/Python/2.7/site-packages/peewee.py", line 2628, in _execute
return self.database.execute_sql(sql, params, self.require_commit)
File "/Library/Python/2.7/site-packages/peewee.py", line 3461, in execute_sql
self.commit()
File "/Library/Python/2.7/site-packages/peewee.py", line 3285, in __exit__
reraise(new_type, new_type(*exc_args), traceback)
File "/Library/Python/2.7/site-packages/peewee.py", line 3454, in execute_sql
cursor.execute(sql, params or ())
peewee.IntegrityError: NOT NULL constraint failed: diary.entries
答案 0 :(得分:0)
您需要将条目设置为null=True
或使用条目的默认值:
class Diary(Model):
entries = TextField(null=True)
输出:
Enter '2' to quit
1) to add an entry
1
Enter your entry, press ctrl+d when done
foobar
Save entry?[1 = yes 0 = no] 1
Saved successfully!
您希望在数据库中看到"entries" TEXT
而不是"entries" TEXT NOT NULL
。如果列设置为NOT NULL
,则必须插入值,否则将出现完整性错误,另一种方法是为列提供默认值,即TextField(default="foo")
。在旁注中,你有#!/usr/bin/env python3
作为你的shebang,但你的代码是为python 2编写的,所以你可能想要纠正它。