简体   繁体   English

Flask send_file 和 send_from_directory 导致会话 cookie 过大

[英]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:当使用flask run时,它不会在我的本地服务器上发生,但是当使用gunicorn 和nginx 时,我使用flask send_file()方法或send_from_directory()来允许用户下载.pdf 文件我崩溃了这个错误:

/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.我尝试更新我的 nginx 配置以允许更大的 cookie,但这不起作用,也不是理想的解决方案。 What am I missing?我错过了什么? Is this an issue with nginx or with the way I call the flask method?这是nginx的问题还是我调用flask方法的方式? The .pdf file is not too big only ten pages long. .pdf 文件不太大,只有十页长。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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