Q:

Python calling one function form another

I have written a little python script to get files in a directory, get a hash and then write them to a table.
The first part, getting the files and calculating the hash was easy. But now I added the function (write_record) to store the filename, log date and hash to a database. But I am struggling how to call it form the get_files function an write a record for each file in the directory
from datetime import datetime
from os import scandir
import os
import hashlib
import psycopg2
BLOCKSIZE = 65536
hasher = hashlib.sha256()
basepath = '.'

def convert_date(timestamp):
     d = datetime.utcfromtimestamp(timestamp)
     formated_date = d.strftime('%d%m%Y%H%M%S')
     return formated_date

def get_hash(entry):
    with open(entry, 'rb') as afile:
        buf = afile.read(BLOCKSIZE)
        while len(buf) > 0:
            hasher.update(buf)
            buf = afile.read(BLOCKSIZE)
                               # print(hasher.hexdigest())

def get_files():
    dir_entries = scandir('.')
    for entry in dir_entries:
        if entry.is_file():
             info = entry.stat()
        print(' %s %s %s' % (entry.name, convert_date(info.st_mtime),hasher.hexdigest())) 
        log_filename = entry.name
        log_hashvalue = hasher.hexdigest()
        log_date = convert_date(info.st_mtime)
        return log_filename,log_hashvalue,log_date
       # write_record()

def write_record():
    log_filename,log_hashvalue,log_date = get_files()
    try:
        print(log_filename,log_hashvalue,log_date)
        connection = psycopg2.connect(user="postgres",password="xxxxxxxx",host="xxx.xxx.xxx.xxx",port="5432",database="evidence_logging")
        cursor = connection.cursor()
        postgres_insert_query = """ INSERT INTO logfiles (log_name,log_date,log_hashvalue) VALUES (%s,%s,%s)"""
        record_to_insert = (log_filename,log_date,log_hashvalue)
        print(postgres_insert_query, record_to_insert)
        cursor.execute(postgres_insert_query, record_to_insert)
        connection.commit()
        count = cursor.rowcount
        print (count, "Record inserted successfully into logfiles table")

    except (Exception, psycopg2.Error) as error :
        if(connection):
            print("Failed to insert record into logfiles table", error)

    finally:
    #closing database connection.
        if(connection):
            cursor.close()
            connection.close()
            print("PostgreSQL connection is closed")

write_record()

Thanks in advance
Regards
Georg

A:

In your code you are calling write_record() method this will insert only one file beacause get_files() method will return the first file not all the files.
first you need to call get_files() method instead of returning in this method you should call write_record() method with the values you are returning from get_files().
And do not close the connection after insertion of every record close the connection after insertion of all the records.
try this
from datetime import datetime
from os import scandir
import os
import hashlib
import psycopg2
BLOCKSIZE = 65536
hasher = hashlib.sha256()
basepath = '.'
connection = None

def convert_date(timestamp):
    d = datetime.utcfromtimestamp(timestamp)
    formated_date = d.strftime('%d%m%Y%H%M%S')
    return formated_date

def get_hash(entry):
    with open(entry, 'rb') as afile:
    buf = afile.read(BLOCKSIZE)
    while len(buf) > 0:
        hasher.update(buf)
        buf = afile.read(BLOCKSIZE)
        # print(hasher.hexdigest())

def get_files():
    dir_entries = scandir('.')
    for entry in dir_entries:
        if entry.is_file():
          info = entry.stat()
        print(' %s %s %s' % (entry.name, convert_date(info.st_mtime),hasher.hexdigest())) 
        log_filename = entry.name
        log_hashvalue = hasher.hexdigest()
        log_date = convert_date(info.st_mtime)
        write_record(log_filename,log_hashvalue,log_date)
    #close the connection after writing all records
    close_connection()

def write_record(log_filename,log_hashvalue,log_date):
    try:
        print(log_filename,log_hashvalue,log_date)
        connection = psycopg2.connect(user="postgres",password="xxxxxxxx",host="xxx.xxx.xxx.xxx",port="5432",database="evidence_logging")
        cursor = connection.cursor()
        postgres_insert_query = """ INSERT INTO logfiles (log_name,log_date,log_hashvalue) VALUES (%s,%s,%s)"""
        record_to_insert = (log_filename,log_date,log_hashvalue)
        print(postgres_insert_query, record_to_insert)
        cursor.execute(postgres_insert_query, record_to_insert)
        connection.commit()
        count = cursor.rowcount
        print (count, "Record inserted successfully into logfiles table")

    except (Exception, psycopg2.Error) as error :
        if(connection):
            print("Failed to insert record into logfiles table", error)

    finally:
        cursor.close()

def close_connection():
    if(connection):
        connection.close()
        print("PostgreSQL connection is closed")

get_files()

