Django: signal when user logs in?

前端 未结 7 1904
予麋鹿
予麋鹿 2020-11-29 19:25

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

7条回答
  •  执念已碎
    2020-11-29 20:14

    In addition to @PhoebeB answer: you can also use @receiver decorator like this:

    from django.contrib.auth.signals import user_logged_in
    from django.dispatch import receiver
    
    @receiver(user_logged_in)
    def post_login(sender, user, request, **kwargs):
        ...do your stuff..
    

    And if you put it into signals.py in your app dir, then add this to apps.py:

    class AppNameConfig(AppConfig):
        ...
        def ready(self):
            import app_name.signals
    

提交回复
热议问题