为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
慕虎7371278 2021-12-08 10:16:33
我正在通过从网站上的用户获取输入文件并对其进行处理来创建数据框。之后我希望用户将最终结果下载到一个 csv 文件中。为此,以前的函数需要一个数据框。我试过传递数据帧,但它给了我错误,因为它是在另一个函数中定义的。我的代码是from flask import Flask, render_template, request, redirectfrom werkzeug import secure_filenameapp = 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 回答

?
阿晨1998

TA贡献2037条经验 获得超6个赞

您还可以将文件存储在服务器上并通过下载 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')


查看完整回答
反对 回复 2021-12-08
?
长风秋雁

TA贡献1757条经验 获得超7个赞

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


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


查看完整回答
反对 回复 2021-12-08
  • 2 回答
  • 0 关注
  • 194 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信