I use Django Rest Framework with rest_auth (/login, /logout/, /register...) I have a Middleware, normally triggered by user_logged_in or user_logged_out signals.
In my Middleware, I want to use Response object from Rest framework.
My middleware.py
from django.contrib.sessions.models import Session
from django.contrib.auth import logout
from django.contrib.auth.models import AnonymousUser
from rest_framework.response import Response
from rest_framework import status
class OneSessionPerUserMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if request.user.is_authenticated:
if request.user.session_key != Session.objects.filter(session_key__in = request.user.session_key):
logout(request)
return Response(request)
return self.get_response(request)
I suppose that I pass my condition, but I get this error :
The response content must be rendered before it can be accessed
How to use correctly the API Response object in a middleware ?
And I don't understand really what is : self.get_response = get_response ?
return Response(request)
. Let your views process the request withreturn self.get_response(request)
. You should handle the logged out case gracefully anyway. – Fiester