'How to fix my flask-session/pymongo error

My flask website is throwing an error with this traceback:

Traceback (most recent call last):
  File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py", line 1537, in finalize_request
    response = self.process_response(response)
  File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py", line 1886, in process_response
    self.session_interface.save_session(self, ctx.session, response)
  File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask_session/sessions.py", line 456, in save_session
    self.store.update({'id': store_id},
  File "/layers/google.python.pip/pip/lib/python3.9/site-packages/pymongo/collection.py", line 2584, in _call_
    raise TypeError("'Collection' object is not callable. If you meant to "
TypeError: 'Collection' object is not callable. If you meant to call the 'update' method on a 'Collection' object it is failing because no such method exists.

I am using flask-session to store session data inside my MongoDB database. I am sure that the error is inside the flask-session library I'm importing. It is using old pymongo functions. i.e. update rather than update_one / update_many. Below is the save_session method.

def save_session(self, app, session, response):
    domain = self.get_cookie_domain(app)
    path = self.get_cookie_path(app)
    store_id = self.key_prefix + session.sid
    if not session:
        if session.modified:
            self.store.remove({'id': store_id})
            response.delete_cookie(app.session_cookie_name,
                                   domain=domain, path=path)
        return

    httponly = self.get_cookie_httponly(app)
    secure = self.get_cookie_secure(app)
    expires = self.get_expiration_time(app, session)
    val = self.serializer.dumps(dict(session))
    self.store.update({'id': store_id},
                      {'id': store_id,
                       'val': val,
                       'expiration': expires}, True)
    if self.use_signer:
        session_id = self._get_signer(app).sign(want_bytes(session.sid))
    else:
        session_id = session.sid
    response.set_cookie(app.session_cookie_name, session_id,
                        expires=expires, httponly=httponly,
                        domain=domain, path=path, secure=secure)

The flask-session code has worked for over a month without this error occurring but today it is causing the website to crash on load every time.

Can someone answer me this:

  • Is it possible to override the save_session method from the flask-session external library with code inside my main flask python file? ( so i can duplicate the function but with updated pymongo methods)
  • if not. Is there any way I can solve this without removing the MongoDB session storage feature?


Solution 1:[1]

I ran into the same issue. Looks like flask-sessions hasn't given mongo any love for a while. Anyways, I updated the MongoDBSessionInterface methods and it seems to work. Keep in mind this is fairly untested.

def open_session(self, app, request):
    sid = request.cookies.get(app.session_cookie_name)
    if not sid:
        sid = self._generate_sid()
        return self.session_class(sid=sid, permanent=self.permanent)
    if self.use_signer:
        signer = self._get_signer(app)
        if signer is None:
            return None
        try:
            sid_as_bytes = signer.unsign(sid)
            sid = sid_as_bytes.decode()
        except BadSignature:
            sid = self._generate_sid()
            return self.session_class(sid=sid, permanent=self.permanent)

    store_id = self.key_prefix + sid
    document = self.store.find_one({'id': store_id})
    if document and document.get('expiration') <= datetime.utcnow():
        # Delete expired session
        # self.store.remove({'id': store_id})
        self.store.delete_one({'id': store_id})
        document = None
    if document is not None:
        try:
            val = document['val']
            data = self.serializer.loads(want_bytes(val))
            return self.session_class(data, sid=sid)
        except:
            return self.session_class(sid=sid, permanent=self.permanent)
    return self.session_class(sid=sid, permanent=self.permanent)

def save_session(self, app, session, response):
    domain = self.get_cookie_domain(app)
    path = self.get_cookie_path(app)
    store_id = self.key_prefix + session.sid
    if not session:
        if session.modified:
            # self.store.remove({'id': store_id})
            self.store.delete_one({'id': store_id})
            response.delete_cookie(app.session_cookie_name,
                                   domain=domain, path=path)
        return

    conditional_cookie_kwargs = {}
    httponly = self.get_cookie_httponly(app)
    secure = self.get_cookie_secure(app)
    if self.has_same_site_capability:
        conditional_cookie_kwargs["samesite"] = self.get_cookie_samesite(app)
    expires = self.get_expiration_time(app, session)
    val = self.serializer.dumps(dict(session))
    # self.store.update({'id': store_id}, {'id': store_id, 'val': val, 'expiration': expires}, True)
    self.store.update_one({'id': store_id},
        {'$set': {'id': store_id, 'val': val, 'expiration': expires}})
    if self.use_signer:
        session_id = self._get_signer(app).sign(want_bytes(session.sid))
    else:
        session_id = session.sid
    response.set_cookie(app.session_cookie_name, session_id,
                        expires=expires, httponly=httponly,
                        domain=domain, path=path, secure=secure,
                        **conditional_cookie_kwargs)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jakefischer