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

查看:36
本文介绍了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. 查询用户登录状态

在我看来,理想的解决方案是

From my perspective, the ideal solution would be

  1. 每个django.contrib.auth.views.login... views.logout
  2. 发送的信号
  3. 一个方法 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 布尔字段,该字段默认清除,在用户第一次点击登录页面时设置(由 LOGIN_REDIRECT_URL 定义)= '/') 并在后续请求中进行查询.我将它添加到 UserProfile 中,因此我不必仅为此目的从内置 User 模型派生和自定义它.

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.

谁能想到替代方法?

推荐答案

你可以使用这样的信号(我把我的放在models.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 文档: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天全站免登陆