简体   繁体   English

如何使用Flask,postgres和Python上传一个csv文件并将数据输入数据库?

[英]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. 尝试上传一个csv文件,打开它,然后遍历各行以将每个字段插入到postgres数据库中,与此有关,我有2个问题(到目前为止已确定)。 I am using Flask not Django. 我正在使用Flask而不是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. heroku日志没有提供其他反馈,因此即使文件已正确打开和读取,我也不确定。

The csv file is: csv文件是:

first_name last_name email etc. # in all 8 columns
John       Smith     john@website.com

and the python code is: 和python代码是:

@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? 该代码是否正确用于上传,打开和插入?

You haven't indented the for loop body: 您尚未缩进for循环主体:

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! Python可以处理任何一个,但不能同时处理两个!

You're better off using the csv Python library . 最好使用csv Python库 There's no need to try parsing csv files yourself! 无需尝试自己解析csv文件!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM