Last time I converted PDF to text, so this time I will create a CSV reader. The code itself is a file upload, so it looks almost the same.
csvopnener.py
import os
import csv
from flask import Flask, render_template, request, redirect, url_for, send_from_directory, session
from werkzeug.utils import secure_filename
app = Flask(__name__)
UPLOAD_FOLDER = './uploads'
ALLOWED_EXTENSIONS = set(['csv'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SECRET_KEY'] = os.urandom(24)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route('/')
def index():
return render_template('csv.html')
@app.route('/show_csv', methods=['GET', 'POST'])
def show_csv():
if request.method == 'POST':
send_data = request.files['send_data']
if send_data and allowed_file(send_data.filename):
filename = secure_filename(send_data.filename)
send_data.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
f = open('uploads/' + filename, 'r')
f_reader = csv.reader(f)
result = list(f_reader)
return render_template('csv.html', result=result)
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
if __name__ == '__main__':
app.debug = True
app.run()
csv.html
{% extends "base.html" %}
{% block content %}
<form method="post" action="{{ url_for('show_csv') }}" enctype="multipart/form-data">
<input type="file" id="send_data" name="send_data">
<input type="submit" value="Send">
</form>
<div>
{% if result %}
<dl>
{% for i in result %}
<dt>{{ i[0] }}<dt>
<dd>{{ i[1] }}</dd>
{% endfor %}
</dl>
{% endif %}
</div>
{% endblock %}
I prepared a CSV file for such a test.
I felt that it would be nice to add a line to CSV if I customized it.
Recommended Posts