我有一个python flask restful app,我希望通过检查特定医生在特定医生预约是否存在,然后再将其插入数据库
我在post方法中添加了一个if语句,但即使添加新条目也没有任何反应。请帮助我,我做错了什么
def post(self):
"""creation de rendez-vous avec pat_id et doc_id"""
appointment = request.get_json(force=True)
pat_id = appointment['pat_id']
doc_id = appointment['doc_id']
appointment_date = appointment['appointment_date']
a = conn.execute("SELECT count(*) From appointment WHERE doc_id =? AND appointment_date=?",(doc_id,appointment_date,)).fetchone()
if a == 0:
appointment['app_id'] = conn.execute('''INSERT INTO appointment(pat_id,doc_id,appointment_date)
VALUES(?,?,?)''', (pat_id, doc_id,appointment_date)).lastrowid
conn.commit()
return appointment
the POST command is succesful yet nothing adds to the database
我使用的是sqlite3数据库,我用它来连接它:
import sqlite3
import json
with open('config.json') as data_file:
config = json.load(data_file)
conn=sqlite3.connect(config['database'], check_same_thread=False)
conn.execute('pragma foreign_keys=ON')
def dict_factory(cursor, row):
"""rend la base de donn en json"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
conn.row_factory = dict_factory
答案 0 :(得分:0)
fetchone
将返回记录或None
。与0
的比较将始终返回False
,因此插入将永远不会发生。
相反,您应该与None
进行比较:
a = conn.execute(...).fetchone()
if a is None:
...
请注意,这只是部分确保不会创建重复的约会。实际上,如果两个客户试图在同一时间安排预约,则会发生这种情况:
Bob sees there is no appointment
Jane sees there is no appointment
Bob adds an appointment
Jane adds an appointment
对于您来说这可能是一个可接受的罕见边缘情况,但如果不是,您应该在数据库级别强制执行此操作。 More info here.