Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Flask, SQLIte, and CSV: How To Perform Transformation Function on Data In Column of CSV When Reading From CSV

I am trying to import data from CSV in comma delimited file type in Python (Flask, SQLite env) to be inserted into my DB table.

However, once the password column is read in the CSV I want to apply a hash function to that data then insert it into the DB table. How it is now I can only read all inputs and insert them raw with no modifications.

How would I go about implementing this onto the password column?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

cursor.execute('CREATE TABLE IF NOT EXISTS Users(email TEXT NOT NULL PRIMARY KEY, password TEXT NOT NULL);')
file = open('data/Users.csv')
contents = csv.reader(file)
next(contents) # skip header row
insert_records = "INSERT INTO Users(email, password) VALUES(?, ?)"
cursor.executemany(insert_records, contents)

This is the desired effect on the column

password = hashlib.md5(password.encode())

CVS Format

Email, Password
john@yahoo.com, hackme!

to ->

john@yahoo.com, $@RN_SOMEHASH_JW#W

Thank you!

>Solution :

Try building a new iterable with password assignment via list comprehension prior to parameterized SQL. Be sure to use with context manager to close automatically after reading text file.

insert_records = "INSERT INTO Users(email, password) VALUES(?, ?)"

with open('data/Users.csv') as file:
    contents = csv.reader(file)
    next(contents) # skip header row

    # LIST OF TUPLES WITH HASH CONVERSION ON SECOND ITEM
    params = [(row[0], hashlib.md5(row[1].encode())) for row in contents]
    cursor.executemany(insert_records, params)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading