0

我正在通过从网站上的用户获取输入文件并对其进行处理来创建数据框。之后我希望用户将最终结果下载到 csv 文件中。为此,之前的函数需要数据框。

我试过传递数据框,但它给了我错误,因为它是在另一个函数中定义的。

我的代码是

from flask import Flask, render_template, request, redirect
from werkzeug import secure_filename
app = Flask(__name__)


@app.route('/uploader', methods = ['GET','POST'])
def upload():
 new=nrecs[['UserID','ProductID','Rating']]
 new['Recommendations'] = list(zip(new.ProductID, new.Rating))
 res=new[['UserID','Recommendations']]  
 res_new=res['Recommendations'].groupby([res.UserID]).apply(list).reset_index()
 pd.options.display.max_colwidth = 500
 return render_template('simple.html', tables=[res_new.to_html(classes='data')], titles='') 

@app.route('/download-csv', methods = ['GET'])
def download():
return res_new.to_csv('Recommendations.csv')

这是我的代码的一小部分,而不是完整的代码。

当用户点击下载推荐按钮时,它应该下载 csv 文件。

有没有其他方法可以解决它。

4

2 回答 2

2

您还可以将文件存储在服务器上,并在您的下载 csv 路径中将其发送给用户。这是一个发送文件教程

from flask import Flask, render_template, send_file
app = Flask(__name__)

@app.route('/uploader', methods = ['GET','POST'])
def upload():
    new=nrecs[['UserID','ProductID','Rating']]
    new['Recommendations'] = list(zip(new.ProductID, new.Rating))
    res=new[['UserID','Recommendations']]
    res_new=res['Recommendations'].groupby([res.UserID]).apply(list).reset_index()

    # store the dataframe on the server.
    res_new.to_csv('Recommendations.csv')

    pd.options.display.max_colwidth = 500
    return render_template('simple.html', tables=[res_new.to_html(classes='data')], titles='')

@app.route('/download-csv', methods = ['GET'])
def download():

    # return the CSV file to the user here.
    return send_file('Recommendations.csv')
于 2019-03-20T08:28:45.240 回答
0

您可以尝试使用会话对象。请参阅此问题/答案。但是,根据数据框的大小以及您最终要执行的操作,这可能不是最好的方法。如果您尝试设置上传/下载路由,将文件存储在服务器/其他地方,然后在用户请求时将其发送给用户,这可能是一个更好的解决方案。

from flask import Flask, render_template, session
app = Flask(__name__)
# secret key is needed for session
app.secret_key = 'your secret key'

@app.route('/uploader', methods = ['GET','POST'])
def upload():
    new=nrecs[['UserID','ProductID','Rating']]
    new['Recommendations'] = list(zip(new.ProductID, new.Rating))
    res=new[['UserID','Recommendations']]
    res_new=res['Recommendations'].groupby([res.UserID]).apply(list).reset_index()

    session['reco_df'] = res_new

    pd.options.display.max_colwidth = 500
    return render_template('simple.html', tables=[res_new.to_html(classes='data')], titles='')

@app.route('/download-csv', methods = ['GET'])
def download():
    return session['reco_df'].to_csv('Recommendations.csv')
于 2019-03-17T07:31:17.427 回答