0

I have a python flask restful app that I would like to improve by checking if an appointment exists with a specific doctor at a specifique time before inserting it into the database

I added an if statement at the post method but nothing happens even if I add a new entry. Help me please what did I do wrong

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

I am using a sqlite3 database and I'm connecting to it with this:

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
Progger
  • 35
  • 5

1 Answers1

0

fetchone will return a record or None if there isn't any selected. The comparison with 0 will always return False, so the insert will never occur.

Instead you should compare with None:

a = conn.execute(...).fetchone()
if a is None:
    ...

Keep in mind that this is only partially ensuring that no duplicate appointments are created. In reality if two clients try to schedule an appointment at the exact same time this will happen:

Bob sees there is no appointment
Jane sees there is no appointment
Bob adds an appointment
Jane adds an appointment

This may be an acceptably rare edge case for you but if not you should enforce this at the database level. More info here.

Eric Pauley
  • 1,531
  • 1
  • 17
  • 29