pallets / flask

The Python micro framework for building web applications.
https://flask.palletsprojects.com
BSD 3-Clause "New" or "Revised" License
67.87k stars 16.2k forks source link

Avoid opening sessions for static resources #5491

Closed markhobson closed 4 months ago

markhobson commented 4 months ago

Every HTTP request currently results in an HTTP session being opened via SessionInterface.open_session. When a server-side session implementation is used, like Flask-Session, this results in storage writes to update the expiry date. Requests for static resources are also subject to this, which can degrade performance.

It would be useful to easily opt static resources out of sessions. Currently this is only possible with a custom session interface, for example:

class StaticRequestFilteringSessionInterface(SessionInterface):
    def __init__(self, app):
        self._delegate = app.session_interface
        self._exclude_path_prefix = app.static_url_path + "/"

    def open_session(self, app, request):
        if request.path.startswith(self._exclude_path_prefix):
            return self.make_null_session(app)

        return self._delegate.open_session(app, request)

    def save_session(self, app, session, response):
        return self._delegate.save_session(app, session, response)

Configured with:

from flask_session import Session

...
Session(app)
app.session_interface = StaticRequestFilteringSessionInterface(app)
davidism commented 4 months ago

In production, if performance is an issue, you want to serve your static files directly through your HTTP server, not through Flask. Then this doesn't apply anyway. In other cases, you may want to serve static files with other conditions applied, at which point it's not clear sessions should always be excluded. I don't think it's worth adding the complexity of implementation and explanation to Flask itself, especially when it's already possible to write a custom session (a completely supported and intended public API) to do whatever you want for your case.

markhobson commented 4 months ago

Thanks for the swift reply. I appreciate it's not core functionality, perhaps something that Flask-Session would consider instead.

markhobson commented 4 months ago

Raised https://github.com/pallets-eco/flask-session/issues/254.

davidism commented 4 months ago

I don't think it makes sense there either, for the same reasons.