Read CSV files uploaded to Flask without saving

For example, in the official documentation Uploading Files — Flask Documentation, how to save the file uploaded by the save () method on the server Although it has been introduced, I could not find a way to read it as it is without saving the file, so I will leave it as a memorandum.

The entity is a buffered binary stream

In Flask request.files.get () (or request.files.getlist () [i] You can run ) to get the Werkzeug datastructures.FileStorage object. The stream of this object is the stream body of the uploaded file. Furthermore, FileStorage.stream seems to inherit ʻio.BufferedIOBase`, so this stream should be boiled. It seems that you should just bake it.

Read the uploaded CSV

If you want to read the uploaded file as text, it is convenient to make it a text stream with ʻio.TextIOWrapper`. ..

Here is a sample that reads a CSV file uploaded from a client.

import io

from flask import Flask, jsonify, request


@app.route('/upload/', methods=['POST'])
def csv_upload():
    filebuf = request.files.get('csvfile')
    if filebuf is None:
        return jsonify(message='Please specify the file'), 400
    elif 'text/csv' != filebuf.mimetype:
        return jsonify(message='Only CSV files will be accepted'), 415

    text_stream = io.TextIOWrapper(filebuf.stream, encoding='cp932')
    for row in csv.reader(text_stream):
        # do something

    return jsonify(message=f'{filebuf.filename!r}Loaded'), 200

Recommended Posts

Read CSV files uploaded to Flask without saving
How to read CSV files in Pandas
Convert UTF-8 CSV files to read in Excel
2 ways to read all csv files in a folder
[R] [Python] Memo to read multiple csv files in multiple zip files
Use Flask to run external files
Read all csv files in the folder
Automatically update CSV files to AWS DynamoDB
Read and write csv files with numpy
Read Python csv and export to txt
[Introduction to Pandas] Read a csv file without a column name and give it a column name
How to read a CSV file with Python 2/3
I want to visualize csv files using Vega-Lite!
How to read csv containing only integers in Python