Django:当用户登录时发出信号? [英] Django: signal when user logs in?

查看:183
本文介绍了Django:当用户登录时发出信号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Django应用程序中,当用户登录时,我需要开始运行一些定期的后台作业,并在用户注销时停止运行,所以我正在寻找一种优雅的方式来

In my Django app, I need to start running a few periodic background jobs when a user logs in and stop running them when the user logs out, so I am looking for an elegant way to


  1. 获取用户登录/注销的通知

  2. 查询用户登录状态

从我的角度来看,理想的解决方案将是每个<$ c $发送的信号

From my perspective, the ideal solution would be


    < c> django.contrib.auth.views.login 和 ... views.logout
  1. a方法 django.contrib.auth.models.User.is_logged_in(),类似于 ... User.is_active() ... User.is_authenticated()

  1. a signal sent by each django.contrib.auth.views.login and ... views.logout
  2. a method django.contrib.auth.models.User.is_logged_in(), analogous to ... User.is_active() or ... User.is_authenticated()

Django 1.1.1没有这个,我不愿修补来源,并添加它(不知道该怎么做,反正)。

Django 1.1.1 does not have that and I am reluctant to patch the source and add it (not sure how to do that, anyway).

作为一个临时解决方案,我添加了一个默认情况下清除的UserProfile模型的 is_logged_in 布尔字段设置为第一次用户hi登陆页面(由 LOGIN_REDIRECT_URL ='/'定义),并在后续请求中进行查询。我把它添加到UserProfile中,所以我不需要派生和自定义内置的用户模型。

As a temporary solution, I have added an is_logged_in boolean field to the UserProfile model which is cleared by default, is set the first time the user hits the landing page (defined by LOGIN_REDIRECT_URL = '/') and is queried in subsequent requests. I added it to UserProfile, so I don't have to derive from and customize the builtin User model for that purpose only.

我不喜欢这个解决方案。如果用户明确点击注销按钮,我可以清除该标志,但大多数时候,用户只需离开页面或关闭浏览器;在这些情况下清理国旗似乎并不直截了当。另外(虽然数据模型的清晰度,但是), is_logged_in 不属于UserProfile,而在User模型中。

I don't like this solution. If the user explicitely clicks the logout button, I can clear the flag, but most of the time, users just leave the page or close the browser; clearing the flag in these cases does not seem straight forward to me. Besides (that's rather data model clarity nitpicking, though), is_logged_in does not belong in the UserProfile, but in the User model.

任何人都可以想到替代方法?

Can anyone think of alternate approaches ?

推荐答案

你可以使用这样的信号(我把我的模型。 py)

You can use a signal like this (I put mine in models.py)

  from django.contrib.auth.signals import user_logged_in


  def do_stuff(sender, user, request, **kwargs):
      whatever...

  user_logged_in.connect(do_stuff)

请参阅django docs: https://docs.djangoproject.com/en/dev/ref/contrib/auth/#module-django.contrib.auth.signals 和这里 http://docs.djangoproject.com/en/dev/topics/signals/

See django docs: https://docs.djangoproject.com/en/dev/ref/contrib/auth/#module-django.contrib.auth.signals and here http://docs.djangoproject.com/en/dev/topics/signals/

这篇关于Django:当用户登录时发出信号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆