In a flask function which returns `send_file`, the code doesn't appear to run on subsequent requests, yet the file still downloads. Why?

前端 未结 2 1484
无人及你
无人及你 2021-01-28 19:40

I am using a Flask Code with the following route:

@app.route(\'/download\')
def download_file():
    path = \"certificate.docx\"
    print(\"certificate printed\         


        
2条回答
  •  春和景丽
    2021-01-28 20:05

    This problem is most likely caused by caching which is built into Flask. This sets the Cache-Control header, and applies to static files served by Flask, but also the send_file and send_from_directory functions. (reference).

    This would explain the behaviour of the file downloading, but the print statements not running. In fact that request won't even be hitting the server.

    You can visualise this on the network tab of the dev tools:


    You can disable this by setting the following config variable on your app:

    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = -1
    

    The -1 value disables caching.

    You may have to actually clear the browser cache for this setting to take affect, or change the URL of your /download endpoint, although this is inconvenient.

    Note the difference once this is set:

提交回复
热议问题