使用Flask将CSV文件上传到mysql,仅上传第一行

时间:2018-04-20 08:55:49

标签: python mysql csv file-upload flask

我正在创建一段代码,它将获取一个csv文件并将该文件的内容上传到mysql数据库。

我正在使用Flask,Python 2.7和MySQL-python == 1.2.5进行此过程。

目前我有一个脚本(如下所示)可以完成此任务,但是我只能获取csv文件来读取/上传csv文件的第一行。 任何帮助将非常感激。

CSVFILE:

date_time,first_name,surname,address,email
2018/03/23 12:09:10,Steve,Jones,UK,SteveJones@hotmail.com
2018/03/23 12:12:20,Jack,Flipper,UK,JackFlipper@hotmail.com
2018/03/23 12:14:30,Rebecca,Fletcher,France,RebeccaFletcher@hotmail.com
2018/03/23 12:15:10,Aby,Jones,Italy,AbyJones@hotmail.com

PYTHON:

import os
import io
import csv
from flask import render_template, request, redirect, url_for,flash
from flask_login import current_user, login_required
from flask_sqlalchemy import SQLAlchemy
from flask.ext.uploads import UploadSet, configure_uploads, DATA
from werkzeug.utils import secure_filename
from . import upload_csv_blueprint
from .. import db
from .. models import details

@upload_csv_blueprint.route('/upload_csv_layout', methods=['POST' , 'GET'])
@login_required
def upload_csv_layout():

    return render_template('upload_csv.html', title='upload_csv')

@upload_csv_blueprint.route('/upload_csv', methods=['GET','POST'])
def upload_file():
  if request.method == 'POST':
      csvfile = request.files['file']

      reader = csv.DictReader(csvfile)
      data = [row for row in reader]
      for row in data:
          date_time_store = row['date_time']
          first_name_store = row['first_name']
          surname_store = row['surname']
          address_store = row['address']
          email_store = row['email']

          query = details(date_time = date_time_store,first_name=first_name_store,surname=surname_store,address=address_store,email=email_store)
          db.session.add(query)
          db.session.commit()
          return('Did it work?')
  else:
      return redirect(url_for('upload_csv.upload_csv_layout'))

HTML OF PAGE:

{% import 'bootstrap/utils.html' as utils %}
{% import 'bootstrap/wtf.html' as wtf %}
{% extends '/advanced_banner.html' %}
    {% block body %}
      <title> Upload CSV </title>
            <form method=POST enctype=multipart/form-data action='/upload_csv'>
                <input type='file' name='file' class='UCSV_FileInput'></input>
                    <button type='submit' value='Upload'>Submit</button>
            </form>
        </div>
        <div class='flash_holding_box'>
            <div class='flash'><b> Action Log </b> <br>{{utils.flashed_messages()}}</div>
        </div>
    {% endblock %}

了解我的导入有点古怪,但一直在尝试一些不同的技术。

0 个答案:

没有答案