简体   繁体   中英

Flask send_file and send_from_directory cause session cookie to be too large

Hi this is a bit of a strange issue. It doesn't occur on my local server when running with flask run but when using gunicorn and nginx the flask send_file() method or send_from_directory() which I use to allow users to download a .pdf file I crash with this error:

/home/ben/newvenv/lib/python3.7/site-packages/werkzeug/wrappers/base_response.py:479: UserWarning: The "b'session'" cookie is too large: the value was 10004 bytes but the header required 26 extra bytes. The final size was 10030 bytes but the limit is 4093 bytes. Browsers may silently ignore cookies larger than this.
  samesite=samesite,

Here is the code where I call this method:

return send_from_directory(directory= directory,filename=filename, as_attachment=True)

I tried updating my nginx config to allow for larger cookies but this didn't work and also is not an ideal solution. What am I missing? Is this an issue with nginx or with the way I call the flask method? The .pdf file is not too big only ten pages long.

I fixed this by clearing the session before sending the file. Here is the code I used to clear the session variables:

def clear_session_variables(exclude=[]):
    """deletes all session variables. Useful to reset before starting new task."""
    print(list(session.keys()))
    for key in list(session.keys()):
        if(key != '_flashes' and key != 'csrf_token' and key not in exclude):
            print(key)
            session.pop(key)
    print(list(session.keys()))

Here is where I call the method:

clear_session_variables(exclude=['db','historical'])
return send_from_directory(directory= directory,filename=filename, as_attachment=True, mimetype='application/pdf')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM