I use alembic - sqlalchemy during operations on Postgresql database. I run the code and the data is successfully written to the database. Later, when I trigger the code again, this time I see that the data in the database has been completely deleted. When I run the code again, I see that the data is written back to the database. The structure in my code works like this.
- If the variable in new_data exists in the current database, update it.
- If the variable in new_data does not exist in the database, write it to the database.
- This variable does not exist in new_data. Delete this variable if it exists in the database.
I don't know where I'm doing wrong in the code, can you help me?
from ConnectDB import create_db_engine
from Models import VirtualServerCustomModel
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
engine, session = create_db_engine()
class VirtualServerCustomService:
def __init__(self):
pass
def get_custom_services(self):
........
def db_process(self):
new_data = self.get_custom_services()
db_data = session.query(VirtualServerCustomModel).all()
# Comparing records in new data records
for veri in new_data:
db_verisi_filtreli = session.query(VirtualServerCustomModel).filter_by(vm_name=veri[2]).first()
if not db_verisi_filtreli:
# If this record does not exist in the database, add the new record
session.add(VirtualServerCustomModel(*veri))
else:
# If there is a record in the database, update it
db_verisi_filtreli.vcenter = veri[0]
db_verisi_filtreli.cluster = veri[1]
db_verisi_filtreli.host = veri[3]
db_verisi_filtreli.power_state = veri[4]
db_verisi_filtreli.vlan = veri[5]
db_verisi_filtreli.ip_address = veri[6]
# Delete records that are in the database but not in the new data
for db_verisi_entry in db_verisi:
if (db_verisi_entry.vcenter,db_verisi_entry.cluster,db_verisi_entry.host,db_verisi_entry.power_state,db_verisi_entry.vlan, db_verisi_entry.ip_address) not in yeni_veri:
session.delete(db_verisi_entry)
session.commit()
session.close()
if __name__ == "__main__":
VirtualServerCustomService().db_process()
If the information in new_data is present in the database, update the record. If the record in new_data is not in the database, write the record to the database. If the record in the database is not in new_data, delete this record from the database.