如何在函数内部创建全局数据框并在 python flask 的另一个函数中使用它

我正在通过从网站上的用户获取输入文件并对其进行处理来创建数据框。之后我希望用户将最终结果下载到一个 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 文件。


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


慕虎7371278
浏览 196回答 2
2回答

阿晨1998

您还可以将文件存储在服务器上并通过下载 csv 路径将其发送给用户。这是发送文件教程from flask import Flask, render_template, send_fileapp = 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, sessionapp = Flask(__name__)# secret key is needed for sessionapp.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')
打开App,查看更多内容
随时随地看视频慕课网APP