使用Django信号识别当前的用户会话

时间:2019-05-27 15:22:51

标签: python django signals

我想使用django信号来识别用户是否两次登录,如果是,请撤消其第一次会话,以便一次只能出现一个用户会话。

我使用了以下示例,但似乎我的signal.py甚至都没有被重新识别,我也不知道为什么。

示例: How to prevent multiple login in Django

accounts / signals.py

from django.contrib.auth import user_logged_in
from django.dispatch.dispatcher import receiver
from django.contrib.sessions.models import Session
from .models import UserSession


@receiver(user_logged_in)
def remove_other_sessions(sender, user, request, **kwargs):
    # remove other sessions
    Session.objects.filter(usersession__user=user).delete()

    # save current session
    request.session.save()

    # create a link from the user to the current session (for later removal)
    UserSession.objects.get_or_create(
        user=user,
        session=Session.objects.get(pk=request.session.session_key)
    )

accounts / models.py

# Model to store the list of logged in users
class UserSession(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    session = models.OneToOneField(Session, on_delete=models.CASCADE)

accounts / apps.py

from django.apps import AppConfig



class AccountsConfig(AppConfig):
    name = 'Accounts'

    def ready(self):
        import Accounts.signals

但是由于某种原因,没有任何内容写入该表的数据库中。

我可能在这里错过了什么吗,这是我第一次与信号联系,所以我可能在配置上错过了什么。

1 个答案:

答案 0 :(得分:0)

尝试一下

import pandas as pd
from pandas import DataFrame, Series
import numpy as np
import time
start_time = time.perf_counter()

file_name= ('A:\somefile.xlsx')
sheet_name= ('6. Data')
data = pd.read_excel(io= file_name, sheet= sheet_name)
data_ltd = DataFrame(data, columns=['year','Approved'])
print("Column list: ",data_ltd.columns.tolist())


data_ltd['Duplicate?']= ~data_ltd.duplicated('year')
print(data_ltd.head())

data_ltd['$$']= data_ltd.groupby('year')['Approved'].transform('sum')
data_ltd['$$']= np.where(data_ltd['$$'].duplicated(), '-',data_ltd['$$'])
print(data_ltd.head(10))

print(time.perf_counter()-start_time)

将此行添加到apps.py文件目录的__init__.py文件中。