0

flaskアプリでアップロードされたcsvファイルを読み込み、それをDataFrameに変換し、別のurlに送るようにしたいです。現在は以下のようなコードでやっています。train_x,train_yなどの部分は見やすさのために省略しております。最終的にy3をgetPlotCSVに送り、それをそのまま出力させたいです。何かいいアイデアをご存じの方はお教えいただければ幸いです。

import os,io
from flask import Flask, flash, request, redirect, url_for, Response, render_template, make_response
from werkzeug.utils import secure_filename
from werkzeug.datastructures import FileStorage
import pandas as pd
import numpy as np
import sklearn
import array
import tempfile

UPLOAD_FOLDER = '/intern/upload'
ALLOWED_EXTENSIONS = {'csv'}

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

#忘れたらflaskの公式見ればある
@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            tempfile_path = tempfile.NamedTemporaryFile().name
            file.save(tempfile_path)
            df1=pd.read_csv(tempfile_path)
            return redirect(url_for('hello',
                                filename=df1))
         
        x2 = df1.drop(columns=[])
          
          
        x4 = x2.dropna(axis=1)

        x6 = np.array(x4)
        x5 = np.array([])

        train_y = np.array([])


    
                
        from sklearn.ensemble import RandomForestRegressor
        rfr = RandomForestRegressor(random_state=0)
        rfr.fit(x5, train_y)

        y_pred = rfr.predict(x6)

        yyy = pd.DataFrame(y_pred)

        y1 = df1[]
        y2 = yyy.iloc[:,0]
        y3 = pd.DataFrame()
        y3[] = y1
        y3[] = y2
        

        
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''

@app.route('/hello')
def hello():
    return '''
        <html><body>
        Hello. <a href="/getPlotCSV">Click me.</a>
        </body></html>
        '''

@app.route("/getPlotCSV/<path:filename>",methods=['GET','POST'])
def getPlotCSV():
    csv = 'unfinished'
    return Response(
        csv,
        mimetype="text/csv",
        headers={"Content-disposition":
                 "attachment; filename=myanswer.csv"})

if __name__ == '__main__':
    app.debug = False
    app.run()

1 件の回答 1

1

こちらの記事を応用してStringIOにDataFrameをto_csv()すれば出来ると思われます。
Writing A Pandas DataFrame To A Disk File Or A Buffer

Example - To write a pandas DataFrame into a text buffer:
This Python example passes an instance of a text stream like StringIO() to write the DataFrame as a CSV into the in-memory text buffer.

from io import StringIO

textStream = StringIO();
y3.to_csv(textStream, index=False); ## y3 をgetPlotCSV():でも使えるようにしておく

return Response(
    textStream.getvalue(), ## StringIOからテキスト取得
    mimetype="text/csv",
    headers={"Content-disposition":
             "attachment; filename=myanswer.csv"})

試してみてください

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。