2

First, please don't shoot me if this has already been asked - I have looked around but to no avail.

I have a python file (named rpc.py) containing many functions serving AJAX requests. For example:

def test(self, vars):
    return vars['id']

def test2(self, vars):
    return vars['id']+1

And it is called with a URL like:

rpc.py?fnc=test2&id=4

I want to call the function that matches the 'fnc' query parameter and pass the whole query string into 'vars'.

So something like the following "pseudocode" is what I am after:

vars = cgi.FieldStorage()
print "Content-Type: text/html\n\n"
print eval('vars["fnc"].value(vars)')

Any ideas?

2
  • 7
    Wow, this is quite possibly the most insecure thing ever. You can (easily I might add) pass arbitrary code to get executed on your server. Never ever use eval. Instead, find a sane way to do it Commented Feb 5, 2011 at 0:00
  • 1
    i appreciate your response but i was after a solution more than just an observation. Commented Feb 5, 2011 at 9:11

1 Answer 1

6

You can use

getattr(server, vars["fnc"])(vars)

but I'd also suggest adding a prefix to the service names (e.g. "do_test") to avoid malicious code that would be able to call any of the methods of the server object simply by passing their names (including ones you think it shouldn't). In this case it would be

getattr(server, "do_" + vars["fnc"])(vars)
Sign up to request clarification or add additional context in comments.

3 Comments

yeah i've heard bad stuff about eval which is why i don't want to use it (albeit i don't fully understand its evil ways), but what exactly is 'server'? i get error "NameError: name 'server' is not defined"
Your functions were accepting a self parameter, so I thought they were methods of a class and that you had a class instance serving requests. I called server the variable holding that class instance.
it works! here is my final code class response: def do_test(self, v): return "test"+str(v['id'].value) def do_test2(self, v): return "test2" if name == "main": vars = cgi.FieldStorage() server = response() print "Content-Type: text/html\n\n" print getattr(server, "do_"+vars["fnc"].value)(vars)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.