Sunday, July 2, 2017

Masking Columns in a database


This simple code was one of my project in fiverr.com, a project worth $20. In this code we have to select a database, find certain values in a column according to id and then replace the value by 'x' or numbers by 'y', so that it will be safe. The other part of the code is to keep the original data in a backup file so that we get the data when needed. Look at the code , and see the comments for better understanding of the code

-

See below is the program named databasemask.py , a program which is responsible for masking and backing up the data which will be replaced. Here, in this particular problem we have the database with tables album,customer and invoice , so we declare three dictionaries to hold their values. Lets divulge the secret of the code with comments now -


##As Described above they are for the tables in the database
album = {}
customer = {}
invoice = {}

class Cipherise(): 

"""This class  is for replacing characters with 'x' and numbers with 'y' for a particular column of the table"""
    def __init__(self, key, *the_phrase):

##Initialize with key, and the_phrase, as the_phrase can be a dictionary or a list we use *
        self.num = key
        self.the_phrase = the_phrase
        self.orginal_phrase = the_phrase #retain the initial value in the orginal_phrase value
        self.converted_phrase = ""#initialize converted_phrase with blank string value 

    def __str__(self):
        return """This is for substituting characters with X and numeric with Y"""

    # def convert(self): #You can use this function if you a pass only string ,not a list  to the database
    #     for i in self.the_phrase:
    #
    #         try:
    #             i = int(i)
    #             i = 'Y'
    #             self.converted_phrase += i
    #         except:
    #             i = 'X'
    #             self.converted_phrase += i
    #
    #     return self.converted_phrase

    def convertall(self): ##This is responsible for converting
        maskedlist = [] ## we create an empty masked list
        for phrase in self.the_phrase: ##we peruse through the phrase, remember here the dictionary is supplied
            # print "the phrase as whole",self.the_phrase #To verify what is passed
            for singlephrase in phrase: #Now we peruse through
                self.converted_phrase = '' #start with an empty phrase and then add characters
                for singlechar in singlephrase:
                    try:
                        singlechar = int(singlechar) #See if it is convertible to integer or not
                        singlechar = 'Y' #if yes, then replace it by Y
                        self.converted_phrase += singlechar #Add the value to converted_phrase
                    # print self.converted_phrase
                    except:
                        if singlechar==" ": #Except add X as a replacement of any character
                            singlechar=" "
                            self.converted_phrase += singlechar
                        else:
                            singlechar="X"
                            self.converted_phrase += singlechar

                print (singlephrase)

                maskedlist.append(self.converted_phrase) #Appending the list to maskedlist List variable

        return maskedlist #Returning the masked list from the function

    def getoriginal(self):
        return self.orginal_phrase #Return the original phrase if needed

    def createdictionary(self):#Testing purpose, as here we have a album table this will create an album backup
        global album
        album[self.num] = self.orginal_phrase

    def getdictionary(self):
        global data
        return data


def getbackupalbum():
    f = open('album.txt', 'a+')
    for i in album:
        f.write(str(i) + "," + str(album[i]) + "\n")
    f.close()


def getbackupcustomer():
    f = open('customer.txt', 'a+')
    for i in customer:
        f.write(str(i) + "," + str(customer[i]) + "\n")
    f.close()


def getbackupinvoice():
    f = open('invoice.txt', 'a+')
    for i in invoice:
        f.write(str(i) + "," + str(invoice[i]) + "\n")
    f.close()









from databasemask import *
import sqlite3 as db


scope=str(input("Enter the File Name: "))
database=str(input("Enter the database name :"))
try:
    dbase=db.connect(database)
    cur=dbase.cursor()
except:
    print ("No Such Db")

#Divide the file after reading
def update_table(table,column):
    pkid=str(table)+"Id"
    cur.execute('select %s,%s from %s'%(pkid,column,table))
    data=cur.fetchall()
    for data in data:
        id=data[0]
        #print id
        data=(data[1])
        cipherise=Cipherise(id,(data,))
        maskeddata=cipherise.convertall()
        maskeddata=maskeddata[0]
        id=int(id)
        print (maskeddata)
        cipherise.createdictionary()
        table=str(table)
        try:
            cur.execute('update "%s"'%table +'set "%s"'%column+'="%s"'%maskeddata+' where "%s"'%pkid+'="%d"'%int(id))
        except:
            print ("Error")

        dbase.commit()
    print ("Job Done")

try:
    f=open(scope,'r')
except IOError:
    print ("No such file")
for line in f:
    columnames ={}
    line=line.strip()
    try:
        line=line.split(':')
        table_name=line[0]
        column_names=line[1]

        try:
            column_names=column_names.split(',')
            for column in column_names:
               update_table(table_name,column)
    #             columnames[i]=column_names[i]
        except:
            columnames.append(column_names)
     #       continue
    #     print columnames
    except:
        continue
f.close()
dbase.close()

No comments:

Post a Comment

Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...