Skip to content

Instantly share code, notes, and snippets.

@voldmar
Last active February 2, 2024 12:17
  • Star 10 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save voldmar/1264102 to your computer and use it in GitHub Desktop.
Show all signals receivers in Django project (quickfixed to work with Django 1.10)
# coding:utf-8
from sys import modules
import gc
import inspect
import six
from django.core.management.base import BaseCommand
from django.dispatch.dispatcher import Signal, WeakMethod
FORMATS = {
'vim': '{path}:{line}:{name}',
'human': '{name} in line {line} of {path}',
}
class Command(BaseCommand):
help = 'Show all signals receivers'
def add_arguments(self, parser):
parser.add_argument('--line_format', choices=FORMATS.keys(), default='human',
help='Line format (available choices: {0})'.format(', '.join(FORMATS))
)
def handle(self, *args, **options):
line_format = options['line_format']
if line_format not in FORMATS:
raise CommandError('format must be on of {0}, not {1}'.format(line_format, FORMATS.keys()))
msg = FORMATS[line_format]
signals = [obj for obj in gc.get_objects() if isinstance(obj, Signal)]
for signal in signals:
for receiver in signal.receivers:
_, receiver = receiver
func = receiver()
name = func.__qualname__ if six.PY3 else func.__name__
print(msg.format(name=name, line=inspect.getsourcelines(func)[1], path=inspect.getsourcefile(func)))
@hugorodgerbrown
Copy link

@voldmar - this is really helpful - thanks for posting. Is it possible to get the name of the Signal as well as the receiver function - I've tried myself but can't work out how to do it.

@bartekbrak
Copy link

Can you please indicate, preferably in-line, what Django version this relates to (or was tested on). It does not work on 1.7 for me (ImportError: cannot import name saferef)

@runekaagaard
Copy link

I made a fork here https://gist.github.com/runekaagaard/2eecf0a8367959dc634b7866694daf2c that lists only model signals by model and signal type. Tested with django 1.7.

@voldmar
Copy link
Author

voldmar commented Feb 14, 2017

@runekaagaard Oh, thank you! I haven’t used Django for a while and haven’t seen comments. Thanks a lot for you fork

@emorozov
Copy link

emorozov commented May 9, 2020

What's the license for this file? Is it public domain?

@voldmar
Copy link
Author

voldmar commented May 10, 2020

@emorozov sure, I think it should be public domain

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment