提问者:小点点

如何在函数中使数据帧成为全局的,并在python中的另一个函数中使用它


我创建一个Dataframe从用户在网站上的输入文件和处理它。之后,我希望用户下载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文件。

有没有其他方法可以解决这个问题。


共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')

匿名用户

您可以尝试使用会话对象。看这个问题/答案。但是,根据数据帧的大小以及最终要做的事情,这可能不是最好的方法。如果您试图设置上载/下载路由,将文件存储在服务器/其他位置,然后在用户请求时将其发送给用户可能是更好的解决方案。

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')