Efficiency
Efficiency – 5 minutes
There’s no need to recreate the database every time we run our program. So let’s check whether the database exists and only create a database if it doesn’t exists.
We can start by renaming our setup_database() where it’s defined and where it’s called.
## from:
## def setup_database():
## to:
def create_database_if_necessary():
...
def main():
create_database_if_necessary() ## this was: setup_database()
read_from_all_devices()
Pretty straightforward to do the bit of renaming. The next part is pretty straightforward too. We need to check whether the database file exists and then react accordingly, only creating the database if we need it.
def create_database_if_necessary():
if os.path.exists(database_name):
print("Database {0} already exists.".format(database_name))
else:
print("Setting up database {0}".format(database_name))
conn = sqlite3.connect(database_name)
c = conn.cursor()
c.execute('''DROP TABLE IF EXISTS devices''')
c.execute('''CREATE TABLE devices (host_name text, user_name text, password text, protocol_type integer)''')
devices = [
('10.62.1.254', 'testpix', 'testpix', HostProtocol.telnet.value),
('10.62.1.254', 'testpix', 'testpix', HostProtocol.ssh.value)
]
c.executemany("INSERT INTO devices (host_name, user_name, password, protocol_type) VALUES (?, ?, ?, ?)", devices)
conn.commit()
We’ve added an if statement that uses a built-in Python function (os.path.exists()) to see whether the database file exists. If it does exist then we just print a little message on the screen. If it does not exist then we go through the same steps we had followed in our old setup_database()implementation.
