73024
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()
    
    
```
CC BY-SA 4.0
2021-01-02T06:31:11.530
73023
2021-01-02T06:56:31.073
43286
question
python flask python-requests
flaskで作成したDataFrameをcsvにして、ダウンロードさせたい。
こちらの記事を応用してStringIOにDataFrameをto_csv()すれば出来ると思われます。  
[Writing A Pandas DataFrame To A Disk File Or A
Buffer](https://pythontic.com/pandas/serialization/to_csv)

> **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"})
    
```

**試してみてください**
CC BY-SA 4.0
2021-01-02T06:56:31.073
73024
2021-01-02T06:56:31.073
26370
73023
answer