Save Django session data after login?

I recently wrote a shopping cart code, which depends on the Session object. This is a smart way to store data for anonymous users.

During testing, I encountered an annoying problem - when users subscribe partially through the verification process (or just browse other products), Django issues a new session_key, and I lose access to my data session.

Is there a way to keep old session data? Or is my design wrong?

+5
source share
3 answers

Try writing your own SessionBackend, which inherits from the existing one and overrides the method cycle_key.

1 V settings.py:

SESSION_ENGINE = 'my_app.session_backend'

2 my_app.session_backend.py:

from django.contrib.sessions.backends.db import SessionStore as DbSessionStore

class SessionStore(DbSessionStore):
    def cycle_key(self):
        pass

cycle_key login .

, ;)

+2

- . Django session_key , . - . request.session['visitor_id']:

from django.utils.crypto import get_random_string
import string

VALID_KEY_CHARS = string.ascii_lowercase + string.digits

def example_view(request):
    if not request.session.get('visitor_id'):
        self.request.session['visitor_id'] = get_random_string(32, VALID_KEY_CHARS)
    # Now code the rest of the view, using the visitor_id instead of
    # session_key for keys in your model.
    # ...
0

Instead of disconnecting cycle_key()(which is a security measure to prevent session fixing vulnerabilities), you might consider restoring values ​​through the decorator in loginand views logout. Cm:

fooobar.com/questions/1124435 / ...

0
source

All Articles