Django: setting a session and getting session key in same view

前端 未结 2 1788
小鲜肉
小鲜肉 2020-12-28 14:53

I want to store some things in a database, and am using the current session as a foreign key: from models.py

class Visited(models.Model):
    session = model         


        
相关标签:
2条回答
  • 2020-12-28 15:38

    request.session is a SessionStore object with a unique session_key.

    The session_key is created as soon as the attribute is accessed. But the session object itself is only saved to the database after the view has been processed (in the process_response method of the session middleware) by calling the save method of the SessionStore object.

    It's not really documented, but looking at the source code I guess you are supposed to create a new session object like this:

    if not request.session.exists(request.session.session_key):
        request.session.create() 
    

    You could also create custom session middleware, that makes sure your new session object is always available before any of your views tries to access it:

    from django.conf import settings
    from django.contrib.sessions.middleware import SessionMiddleware
    
    class CustomSessionMiddleware(SessionMiddleware):
        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)
            if not request.session.exists(request.session.session_key):
                request.session.create() 
    

    (Of course you must reference your new session middleware via the SESSION_ENGINE inside your settings.py)

    But be aware - this approach will generate a new session object for every request if the user's browser does not support cookies ...

    0 讨论(0)
  • 2020-12-28 15:46

    if you want to destroy session i would suggest a better idea is first use django shell.

    from django.contrib.sessions.models import Session
    Session.objects.all() #you see all sessions
    Session.objects.all().delete() 
    

    in last query you can filter according to your need. and hit a query

    0 讨论(0)
提交回复
热议问题