问题
This is my second question today actually but what I want to know...Is it possible to retrieve information from a signal handler.
I have a list of items, call it list and each item is in AppA. Each item has a couple of characteristics which are saved in a different app, AppB.
So, I figured that I could maybe create a dictionary, dict and iterate over the items in list. In each iteration, I was hoping to send a signal to AppB and retrieve the information, i.e. have something like
def blob(request):
dict = {}
for item in list:
signal.send(sender=None, id=item.id)
dict[item] = (char1, char2)
...some html request
My signal handler looks something like this:
def handler(sender, id, **kwargs):
model2 = Model2.objects.get(id=id)
a = model2.char1
b = model2.char2
return (a, b)
Then I was hoping to be able to just produce a list of the items and their characteristics in the webpage...THe problem is that obviously the signal sender has to send the signal, and get the information back which I want....is that even possible :S?
Currently, I get an error saying "global name 'char1' is not defined....and I have imported the handlers and signals into the view.py where blob resides....so is my problem just unsolvable? / Should it clearly be solved in another way? Or have I almost certainly made a stupid error with importing stuff?
回答1:
This wasn't actually so tricky. Thought I should perhaps post how it was solved. In my views, I actually wrote
response_list=signal.send(sender=None, list=list_of_items)
I then iterated over my response_list, adding the items to a fresh list like so:
snippets = []
for response in response_list:
logger.error(response)
snippets.append(response[1])
And could then call the responses in snippets like a dictionary in my template. When I asked the question, I didn't appreciate that I could equate something with the signal sending...
来源:https://stackoverflow.com/questions/17555175/getting-information-from-django-custom-signal-receiver