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.
I get an indentation error, although I cannot for the life of me see where. RESOLVED
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 john@website.com
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:
what is the indentation problem? RESOLVED
Is the code correct for uploading, opening and insertion?
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.