database.py (1363B)
1 from models import Project 2 import sqlite3 3 import json 4 5 6 class Database: 7 def __init__(self): 8 self.connection = sqlite3.connect("database.db", check_same_thread=False) 9 self.cursor = self.connection.cursor() 10 self.cursor.execute( 11 """CREATE TABLE IF NOT EXISTS projects ( 12 name text NOT NULL, 13 description text, 14 authors text NOT NULL, 15 source text 16 )""" 17 ) 18 self.write() 19 self.read() 20 21 def __del__(self): 22 self.connection.close() 23 24 def read(self): 25 self.projects = [] 26 self.cursor.execute("SELECT * FROM projects") 27 for data in self.cursor.fetchall(): 28 name = data[0] 29 description = data[1] 30 authors = json.loads(data[2]) 31 source = data[3] 32 project = Project(name, description, authors, source) 33 self.projects.append(project) 34 return self.projects 35 36 def write(self): 37 self.connection.commit() 38 39 def add(self, project): 40 self.projects.append(project) 41 data = ( 42 project.name, 43 project.description, 44 json.dumps(project.authors), 45 project.source, 46 ) 47 self.cursor.execute("INSERT INTO projects VALUES (?, ?, ?, ?)", data) 48 self.write() 49 50 51 database = Database()