2
votes

I have some static files I've been serving through Flask. On a given request, I run some processing and authentication, and then serve the file. I've been doing that using Flask's send_from_directory, but it looks like that caches the file for a bit, which is no good for me. I have Flask running behind nginx, so I'm open to serving partially through nginx, but I need to run processing/authentication before the file gets served.

So, the main question is, how do I serve uncached static files with Flask and nginx assuming I need to do processing/authentication in Flask before serving?

Note: I've seen answers detailing how to serve files just through nginx, but that's no good for me because I have to do processing in Flask before serving.

1
Authentication can be done using auth_request module nginx.org/en/docs/http/ngx_http_auth_request_module.htmlAnatoly

1 Answers

4
votes

By default flask caches files that you send using send_from_directory for 12 hours. You have at least a couple of options to overcome this behavior.

You can change the config value SEND_FILE_MAX_AGE_DEFAULT to something less like 1 or 0 seconds which will impact the default value used for the entire application. Or, you could pass it directly to send_from_directory call you do not want a cache for using the keyword cache_timeout.

e.g.,

 @app.route('/uploads/<path:filename>')
 def download_file(filename):
     return send_from_directory(app.config['UPLOAD_FOLDER'],
                                filename, cache_timeout = 0)

Or you could subclass Flask and override the get_send_file_max_age method.