It seems like you've encountered a common issue when dealing with CORS and the OPTIONS pre-flight requests. Like you, I also struggled to find a direct solution in the Flask_session documentation or elsewhere online. However, I did manage to devise a workaround that might serve your needs.
Essentially, I created a custom session interface that treats OPTIONS requests differently, specifically by creating non-permanent sessions for these requests. Although this is not an ideal solution, it does prevent the creation of database records for these sessions, thus reducing strain on your server. Here's how to do it:
Firstly, you'll need to override the open_session
method in the SqlAlchemySessionInterface
class from flask_session
. This will allow you to check if the request method is 'OPTIONS' and create a non-permanent session if so:
from flask_session import SqlAlchemySessionInterface as FlaskSessionSqlAlchemySessionInterface
class SqlAlchemySessionInterface(FlaskSessionSqlAlchemySessionInterface):
def __init__(self, app, db, table, key_prefix):
super().__init__(app, db, table, key_prefix)
def open_session(self, app, request):
if request.method == 'OPTIONS':
sid = self._generate_sid()
return self.session_class(sid=sid, permanent=False)
return super().open_session(app, request)
Then, in your application factory, assign this custom interface to your app's session interface:
app.session_interface = SqlAlchemySessionInterface(app, db, 'sessions', 'session:')
If you are not using SqlAlchemy, then you need to extend the proper class. You can see all the implementations in the flask_session repository.