0

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?

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

4 Comments

thanks I should add that I did import cvs. I will check the tabs and spaces, as you suggest. And the rest? Does it look correct at least in terms of approach?
Thank you, indentation is resolved. However, the upload and insertion does not work. Heroku gives no reason why, just a 500 response. Please could you give me your view on the code which I have now amended above? Thank you!
If you're getting a server error, check your logs for the error message.
thanks but the heroku logs say nothing just "status 500"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.