我正在尝试使用django和django rest框架检查并显示用户在线状态。
我已经尝试过这篇文章:Django - detect if user is online / offline 但不适用于APIview,仅适用于具有render和Httpresponse的视图。
已更新
这是中间件类的代码
import datetime
from django.core.cache import cache
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
class ActiveUserMiddleware(MiddlewareMixin):
def process_request(self, request):
current_user = request.user
if request.user.is_authenticated:
now = datetime.datetime.now()
cache.set('seen_%s' % (current_user.username), now, settings.USER_LASTSEEN_TIMEOUT)
APIView 类ProfilePersonal(APIView): Permission_classes =(permissions.IsAuthenticated,)
serializer_class = UserProfileSerializer
def get(self):
try:
queryset = Account.objects.get()
except Account.DoesNotExist:
return Response(data={'non_field_errors': 'Request could not be validated.'},
status=status.HTTP_400_BAD_REQUEST)
serializer_data = self.serializer_class(queryset)
return Response(
data=serializer_data,
status=status.HTTP_200_OK
)