On Thu, 2009-02-19 at 00:43 +0100, Nicolas Steinmetz wrote: [...] > The issue is that engine in engine(request.POST['search'], 10) does not > become google(request.POST['search'], 10) in the case where the user > chosed "google" as engine. > > Is there a solution or did I have to test all values with a if or case > loops ?
Two solutions spring to mind. The problem you are trying to solve is: given a string naming a function, call that function. So you have to map the string name to the function object. Method #1: use the globals() dictionary to look up the function object. globals()[engine](....) The drawback here is that you should still sanitise the contents of "engine", since otherwise the POST data could be used to call anything in your globals() namespace. That could be a denial-of-service attack, at a minimum (a security exploit at worst). Method #2: create a dictionary mapping "engine" values to the right callable. try: {'google': google, 'yahoo': yahoo, # ... }[engine](...) except KeyError: # Engine name is not valid. Handle appropriately here. The drawback is the percieved redundancy between the string name and the function name. Still, I would prefer this solution. It automatically only allows "permitted" value through -- and if, say, you wanted to temporariliy disable the yahoo functionality, you would just comment out or remove that line from the dictionary. It also means you don't *have* to call your functions by the same name as the search engine, which would be useful if you ever included an engine whose name was not a valid Python identifier, for example. By the way, this second pattern is more-or-less idiomatic Python for a C-style switch-statement. Usually preferable to a series of if...elif... statements, particularly for a large number of choices. Regards, Malcolm --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---