user1903663
user1903663

Reputation: 1725

how can I upload a csv file and enter the data into a database, using Flask, postgres and Python?

Trying to upload a csv file, open it and then iterate through the rows to insert each field in to the postgres database, I have 2 (identified so far) problems with this. I am using Flask not Django.

  1. I get an indentation error, although I cannot for the life of me see where. RESOLVED

  2. The heroku logs provide no other feedback so I am unsure even if the file is correctly opened and read.

The csv file is:

first_name last_name email etc. # in all 8 columns
John       Smith     [email protected]

and the python code is:

@app.route("/uploadcsv", methods=['POST'])
def uploadcsv():
csvfile = request.files['file']
with open(csvfile):
    reader = csv.DictReader(csvfile)
    for row in reader:
        firstname = row['first_name']
        query = Prospect(first_name=firstname)
        db.session.add(query)
        db.session.commit()
        return "OK"

So, there are 2 questions:

  1. what is the indentation problem? RESOLVED

  2. Is the code correct for uploading, opening and insertion?

Upvotes: 0

Views: 2815

Answers (1)

Karl Barker
Karl Barker

Reputation: 11341

You haven't indented the for loop body:

for row in data:
    first_name = row['first_name']
    sql = Prospect(first_name=first_name) #truncated for brevity
    db.session.add(sql)
    db.session.commit()

If it's not that, then it's probably mixed tabs and spaces. Python can handle one or the other, but never both!

You're better off using the csv Python library. There's no need to try parsing csv files yourself!

Upvotes: 1

Related Questions