信号处理程序应该放在 django 项目中的什么位置? [英] Where should signal handlers live in a django project?

查看:18
本文介绍了信号处理程序应该放在 django 项目中的什么位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始在 django 项目中实现信号监听器.虽然我了解它们是什么以及如何使用它们.我很难弄清楚我应该把它们放在哪里.来自 django 网站的文档是这样说的:

I have just started implementing signal listeners in a django project. While I understand what they are and how to use them. I am having a hard time figuring out where I should put them. The documentation from the django site has this to say:

这段代码应该放在哪里?

你可以把信号处理和您喜欢的任何地方的注册码.但是,您需要确保它所在的模块会提前导入on 以便信号处理得到在任何信号需要之前注册被发送.这使您的应用程序的models.py 是一个放置的好地方信号处理程序的注册.

You can put signal handling and registration code anywhere you like. However, you'll need to make sure that the module it's in gets imported early on so that the signal handling gets registered before any signals need to be sent. This makes your app's models.py a good place to put registration of signal handlers.

虽然这是一个很好的建议,但在我的 models.py 中包含非模型类或方法只会让我犯错.

While its a good suggestion, having non model classes or methods in my models.py just rubs me the wrong way.

那么,存储和注册信号处理程序的最佳实践/规则是什么?

So then, what is the best practice/rule for storing and registering signal handlers?

推荐答案

我其实很喜欢让它们成为模型本身的类方法.这将所有内容都放在一个类中,这意味着您不必担心导入任何内容.

I actually like to make them classmethods of the model itself. That keeps everything within one class, and means you don't have to worry about importing anything.

这篇关于信号处理程序应该放在 django 项目中的什么位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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