在Django代码的哪里放代码断开信号并做monkeypatching?

2024-07-04 06:14:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为Django 2.2开发自定义授权后端。我不想django为用户更新last_login,所以我想断开信号user_logged_in触发update_last_login。你知道吗

我还必须在SimpleJWT库中进行monkey补丁,更改用户到点OtherUserModel

把代码放在哪里最好?现在,我已经添加了CoreConfig.ready方法,它可以工作,但是它是这个逻辑的好地方吗?你知道吗

from django.apps import AppConfig


class CoreConfig(AppConfig):
    name = 'core'

    def ready(self):
        from django.contrib.auth import user_logged_in
        from django.contrib.auth.models import update_last_login
        user_logged_in.disconnect(update_last_login, dispatch_uid='update_last_login')

        import rest_framework_simplejwt.state
        rest_framework_simplejwt.state.User = OtherUserModel

Tags: django用户infromimportloginupdatecontrib
1条回答
网友
1楼 · 发布于 2024-07-04 06:14:26

我想说是的,但我认为这里没有明确的对错,关于连接信号,Django文件规定如下:

Strictly speaking, signal handling and registration code can live anywhere you like, although it’s recommended to avoid the application’s root module and its models module to minimize side-effects of importing code.

In practice, signal handlers are usually defined in a signals submodule of the application they relate to. Signal receivers are connected in the ready() method of your application configuration class. If you’re using the receiver() decorator, simply import the signals submodule inside ready().

我的观点是,如果建议的连接信号的方法是使用ready()方法连接信号,那么断开信号连接和相关的monkeypatching也应该使用这种方法。你知道吗

我经常做的是:

  1. 除了搞乱默认信号/类之外,还有其他方法解决这个问题吗?你知道吗
  2. 如果不是,请在AppConfig ready()方法中执行此代码
  3. 编写一些单元测试或集成测试,以确保我的代码执行我希望它执行的操作,即使在更新依赖项时也是如此

相关问题 更多 >

    热门问题