亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在函數內部創建全局數據框并在 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 關注
  • 241 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號