2

I have assigned a pandas dataframe globally

df = pd.read_csv('file.csv')

I have a Flask app with a submit route that's triggered once user makes a POST request from the browser.

@app.route('/submit')
def sub():
   // do some filtering in df

   return redirect(url_for('recommend', uid=1))

I would like sub() to pass df to /recommend.

@app.route('/recommend/<int uid>')
def rec(uid):
   // make recommendations based on df

   return df.to_html()

The problem is, how do I pass it? I've tried passing it in the URL query

@app.route('/submit')
def sub():
   // do some filtering in df

   return redirect(url_for('recommend', uid=1, df=df))

@app.route('/recommend/<int uid>/<df>')
def rec(uid,df):
   // make recommendations based on df

   return df.to_html()

But this turns df to a string. I thought the path of least resistance would be to just make df global, but any local manipulations to df inside sub() are not getting picked up globally.

pairwiseseq
  • 313
  • 2
  • 13

2 Answers2

1

Assigning df as global is not an effective solution in most cases. There are many ways you can use a dataframe across different methods/routes in a flask application: sessions, pickling, converting df to csv/json/dict, or returning it through a function, etc. depending on your dataframe and what you intend to do with it. Here are few examples:

def filter-df():
   df = pd.read_csv('file.csv')
   // do some filtering in df
   return df

@app.route('/submit')
def sub():
   // or you can use session/pickling to cache/store your df after you do some filtering in df
   return redirect(url_for('recommend', uid=1))

@app.route('/recommend/<int uid>')
def rec(uid):
   df = filter-df()
   // make recommendations based on df
   return df.to_html()

Here's a post on how to use session and this one on how to pickle/unpickle.

Singh
  • 504
  • 4
  • 15
0

while setting - session['dataframe'] =x.to_json()

while reading - df_data = pd.read_json(session['dataframe'])

mourya
  • 1
  • 2