Custom Session Engine

Hi, I need help with the implementation of Django Session engine.

I’m using the example from the Django documentation How to use sessions | Django documentation | Django.

Suppose that my sessions engine is saved in the app/custom/sessions.py, and the code is identical to the code provided in the example. What are the further steps of enabling the extended session engine?

Is it enough just to declare in project’s settings.py:

SESSION_ENGINE = "app.custom.sessions"

?

Or there more changes to be applied?

I’m also wondering, if the code for the custom session engine is stored in the django app app/custom/sessions.py. Is the table django_customsession is going to be created?

from django.contrib.sessions.backends.db import SessionStore as DBStore
from django.contrib.sessions.base_session import AbstractBaseSession
from django.db import models


class CustomSession(AbstractBaseSession):
    @classmethod
    def get_session_store_class(cls):
        return SessionStore


class SessionStore(DBStore):
    @classmethod
    def get_model_class(cls):
        return CustomSession

Thank you in advance for your help!

Have you tried it to see what happens? That’s one of the quickest/easiest ways to find answers to questions like this.

Yes, it is not working for me. I get an error: OperationalError: no such table: app_customsession.
Any advice how could I make this work? :confused:

Did you do a makemigration / migrate for this app?

Is app the project name and custom the app name? Or is app the app and custom is a directory within the app? If the latter, I’m guessing a makemigrations isn’t seeing that this new model is being defined.

Just taking a wild guess here, you may want to put your CustomSession class in your models.py file. Or, write a custom migration to create the table.

  1. yes, I did migrations for the app
  2. app is the app name, custom is the directory. I also tried app/sessions.py.
  3. You are guessing correctly :slight_smile:
  4. This might work, I have seen a similar solution on the stack overflow, but it seems a bit weird to me, just imagine a huge Django project with the Custom Session engine hidden in one of the multiple apps. Doesn’t look nice… :confused:

I would appreciate your recommendation for setting the Custom Session Engine.

Thanks!

I have no recommendations. I’ve never run into a situation where a custom session engine has ever been necessary or desired.

I’m guessing you could put the model definition in the models.py file and the engine itself somewhere else.

Or, you could possibly create a whole new “custom session” app.

Or you could create your own migration for the model.

Or you could create the table outside of Django and reference it with the table_name attribute in the Meta class.

Functionally, I don’t see any effective difference between any of these options.

Thank you for your help Ken! :slight_smile: