alex-oleshkevich / starsessions

Advanced sessions for Starlette and FastAPI frameworks
MIT License
98 stars 11 forks source link

Potential issue with default values #51

Closed RamiAwar closed 2 years ago

RamiAwar commented 2 years ago

Not sure if this is a bug, just an issue I encountered when working:

When a session is created, I'm adding a default _created date in the _data field:

class Session:
    def __init__(
        self, backend: SessionBackend, session_id: typing.Optional[str] = None
    ) -> None:
        self.session_id = session_id
        self._data: typing.Dict[str, typing.Any] = default_session()
        self._backend = backend
        self.is_loaded = False
        self._is_modified = False

However when the session is loaded, these default values get overwritten by the data loaded from the backend:

    async def load(self) -> None:
        """
        Load data from the backend.

        Subsequent calls do not take any effect.
        """
        if self.is_loaded:
            return

        if not self.session_id:
            self.data = default_session()
        else:
            self.data = await self._backend.read(self.session_id)

        self.is_loaded = True

My solution was to do this instead:

    async def load(self) -> None:
        """
        Load data from the backend.

        Subsequent calls do not take any effect.
        """
        if self.is_loaded:
            return

        if not self.session_id:
            self.data = default_session()
        else:
            # Update data to keep default values
            backend_data = await self._backend.read(self.session_id)
            backend_data.update(self._data)
            self.data = backend_data
alex-oleshkevich commented 2 years ago

This is by design. Backend data has the highest priority. You can implement this feature in a custom backend and override read/write methods to add this extra values.