2

I want to pass a large list between views in Flask however I can't put it in a session because it exceeds the 4096 bytes limit. Is there a way to pass a list between pages through something like a form such as this?

Python:

@app.route('/send')
def send():
  list = ['item1', 'item2', 'item3', 'item4']
  return render_template('send.html', list=list)

@app.route('/receive', methods=['POST', 'GET'])
def receive():
  list = request.form['list']
  return render_template('receive.html')

send.html:

<form method="POST" action="{{ url_for('receive') }}">
  <input type="text" name="list" value="{{ list }}">
  <submit>Submit</submit>
</form>

Would this work? Thanks.

Pav Sidhu
  • 6,724
  • 18
  • 55
  • 110

2 Answers2

5

I had a similar problem passing a large list between views. Here's what I did:

import tempfile
import pickle
import shutil

mylist = ['a', 'b', 'c']

session['tempdir'] = tempfile.mkdtemp()
outfile = open(session['tempdir'] + '/filename', 'wb')
pickle.dump(mylist, outfile)
outfile.close()

To retrieve the list in another view:

infile = open(session['tempdir'] + '/filename', 'rb')
mylist = pickle.load(infile)
infile.close()

And then remember to delete your temp directory, file and clear session when you're done:

shutil.rmtree(session['tempdir'])
session.pop('tempdir', None)
omerk
  • 483
  • 6
  • 8
2

Yes it would work.

However I think it's bad practice. Depending on your usage scenario I would store a unique identifier on the session and then save it to local storage. You could then restore the list in your second view. However you need a scheme to handle the stored lists. When should they be deleted? After usage in the second view? When should a list which was saved to disk, but never used in the second view be deleted? And which process is responsible for it?

Aske Doerge
  • 1,331
  • 10
  • 17
  • How would I save it to local storage using Flask? – Pav Sidhu Nov 15 '15 at 20:20
  • Just like regular python `open(myfile, 'w')`. You can use [tempfile](https://docs.python.org/2/library/tempfile.html#tempfile.mkstemp) to create it, but still need to manage the deletion as mentioned above. – Aske Doerge Nov 15 '15 at 20:58