Time for action connecting to the database

Let's first have a look at the TaskDB class. It consists of a constructor __init__() that takes the filename where the database will reside as a parameter. It calls a private method to initialize this database, and like the LogonDB class, creates some storage to hold connection objects for each thread (highlighted). It also defines a connect() method that should be called once for each thread and stores a thread-specific connection object. It also sets the row_factory attribute of the connection to sqlite3.Row. This causes the tuples returned by, for example, fetchall() to have their fields named after the columns they represent. This makes sense as t['user_id'] is a lot more self documenting than t[1], for example.

Chapter4/tasklistdb.py

class TaskDB:
	def __init__(self,db):
		self.data = threading.local()
		self.db = db
		self._initdb()
	def connect(self):
		'''call once for every thread'''
		self.data.conn = sqlite3.connect(self.db)
		self.data.conn.row_factory = sqlite3.Row

What just happened?

The code for the __init__() method did not initialize any table in the database itself, but delegated this to the _initdb() method. This method starts with an underscore so it is private by convention (but by convention only). It is meant to be called just from __init__() and initializes the database, if necessary. It opens a connection to the database and executes a multiline statement (highlighted). Here we use create if not exists to create the task table, but only if it is not already present. So if we start the application for the first time, the database will be completely empty and this statement will create a new table named task. If we start the application again later, this statement will not do anything. Before closing the connection, we commit our changes.

Chapter4/tasklistdb.py

def _initdb(self):
	'''call once to initialize the metabase tables'''
	conn = sqlite3.connect(self.db)
	conn.cursor().executescript('''
	create table if not exists task (
		task_id integer primary key autoincrement,
		description,
		duedate,
		completed,
		user_id
	);
	'''
	)
	conn.commit()
	conn.close()

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.137.59