4

I am writing an applition where I need to use JavaScript's "Fetch" and because of CORS, all my requests have a pre-flight OPTIONS request. This means that in my session database, it creates a new session everytime an OPTIONS request is made. I do remove sessions after they expire, however, it is tedious and strains the server to remove those useless sessions everytime.

Is there a way for me to specify that flask_session can ignore OPTIONS requests? I have looked everywhere but I can't find a good option and the flask_session documentation isn't much to write home about (you have to manually remove your sessions once expired).

Derekm4n
  • 41
  • 1

1 Answers1

0

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.