From 470e47167897edd2937d719f4a8424a653997ade Mon Sep 17 00:00:00 2001 From: Scot Hacker Date: Tue, 23 Apr 2019 23:27:04 -0700 Subject: [PATCH] Signals demo --- todo/signals.py | 24 ++++++++++++++++++++++++ todo/views/list_lists.py | 6 ++++++ 2 files changed, 30 insertions(+) create mode 100644 todo/signals.py diff --git a/todo/signals.py b/todo/signals.py new file mode 100644 index 0000000..6244982 --- /dev/null +++ b/todo/signals.py @@ -0,0 +1,24 @@ +import django.dispatch +from django.dispatch import receiver + +from todo.utils import toggle_task_completed + +# ### REGISTER SIGNALS ### + +# Demonstrates registering a custom signal +pizza_done = django.dispatch.Signal(providing_args=["toppings", "size", "task_id"]) + + +# ### HANDLE SIGNALS ### + +# Demonstrates receiving a custom signal +# (which in turn calls an existing todo function, but could do anything) +@receiver(pizza_done) +def toggle_task_handler(sender, **kwargs): + print(sender) + print(kwargs) + task_id = kwargs.get("task_id") + results = toggle_task_completed(task_id) + print(results) + + print("Request finished!") diff --git a/todo/views/list_lists.py b/todo/views/list_lists.py index d8b7bea..ee676a5 100644 --- a/todo/views/list_lists.py +++ b/todo/views/list_lists.py @@ -9,6 +9,7 @@ from todo.forms import SearchForm from todo.models import Task, TaskList from todo.utils import staff_check +from todo.signals import pizza_done @login_required @user_passes_test(staff_check) @@ -16,6 +17,11 @@ def list_lists(request) -> HttpResponse: """Homepage view - list of lists a user can view, and ability to add a list. """ + # Demonstrates sending a custom signal from elsewhere in the project. + # In this case when the list of lists is viewed, I'm going to toggle + # the "completed" state of task 150 (just for example's sake). + pizza_done.send(sender="foobar", toppings=["anchovies", "parmesan"], size=7, task_id=150) + thedate = datetime.datetime.now() searchform = SearchForm(auto_id=False)