0

I have a custom session class that I've built to extend the Django SessionBase. I did this in order to reuse a legacy Session table, so that sessions can pass between our Django pages and our PHP pages without having the user to log in and back out.

Everything's working perfectly so, far with one huge BUT.

I wrote some custom middleware in order to let the SessionStore.start() function have access to the Request Object. Unfortunately, in order to do that I used this answer: Access request.session from backend.get_user in order to remedy my problem.

I have learned that using the above answer (Essentially binding the request object to the settings, so you can access using import settings* and then settings.request) is totally horrible and the absolutely worst way to do this.

My core problem, is I don't understand how I can access the request from within the custom session backend I've written.

halfer
  • 19,824
  • 17
  • 99
  • 186
Wade Williams
  • 3,943
  • 1
  • 26
  • 35

2 Answers2

2

Maybe in middleware you could pass request to your custom SessionStore like this:

request.session = engine.SessionStore(session_key,request)

and in SessionStore:

class SessionStore(SessionBase):
    def __init__(self, session_key=None, request):
        self.request = request
        super(SessionStore, self).__init__(session_key)

Later you can access request as self.request.

Bula
  • 1,590
  • 1
  • 14
  • 33
1

Django's SessionMiddleware does this:

class SessionMiddleware(object):
    def process_request(self, request):
        engine = import_module(settings.SESSION_ENGINE)
        session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
        request.session = engine.SessionStore(session_key)

can't you do this?

import mycustomsessionbackend as myengine

class MyCustomSessionMiddleware(object):
    def process_request(self, request):
        session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
        request.session = myengine.SessionStore(session_key, request)

...

# mycustomsessionbackend.py
class SessionStore(SessionBase):
    def __init__(self, session_key=None, request=None):
        super(SessionStore, self).__init__(session_key)
        self.request = request
Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124