请尝试以下代码。
我试过了,效果很好。在
请修复password和host,以及{}的host。在import os
from flask import Flask, request, redirect, url_for, send_from_directory
from werkzeug import secure_filename
import MySQLdb
import glob
UPLOAD_FOLDER ="/tmp/"
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'csv'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
# this has changed from the original example because the original did not work for me
return filename[-3:].lower() in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
print '**found file', file.filename
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
conn = MySQLdb.connect (host="127.0.0.1", port=3306, user="root",passwd="kani",db="myDb", local_infile = 1)
x = conn.cursor()
print 'filename'
sql = """LOAD DATA LOCAL INFILE '{}'
INTO TABLE test
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
"""
os.chdir(UPLOAD_FOLDER)
dirfiles=glob.glob("*.csv")
for file_name in dirfiles:
print file_name
if file_name==filename:
try:
cursor = conn.cursor()
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
print sql.format(file_path)
cursor.execute(sql.format(file_path))
conn.commit()
print "hello"
except Exception, e:
print e
# Rollback in case there is any error
conn.rollback()
# for browser, add 'redirect' function on top of 'url_for'
return url_for('uploaded_file',
filename=filename)
return '''
Upload new FileUpload new File
'''
@app.route('/uploads/')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
if __name__ == '__main__':
app.run(host='192.168.33.40', port=5000, threaded=True,debug=True)
您应该将local_infile = 1插入MySQLdb.connect,以便使用LOAD DATA语句。在
编辑
抱歉,如果只想插入csv文件的路径,则不需要local_infile=1。在
简单地说,请修复您的sql。。在
sql = "INSERT into test (file_path) values ('{}')"
这是你想要的吗?在
编辑
您可以获得如下文件路径。在
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
并且,通过使用format方法
sql.format(file_path)
您的sql如下所示。在
INSERT into test (file_path) values ('/tmp/hoge.csv')
你能试试上面的吗?在
附言
^{pr2}$
我希望一切顺利。在