How to use a string to (safely) access deep Python properties? -


i'm trying find way allow users request arbitrary portions of python object, , have server return data without accidentally allowing them request stuff they're not allowed have or things they're not allowed do.

for example, server has data:

my_stuff = {"alpha": ["bravo", "charlie", {"delta": "echo"}], "foxtrot": "golf"} 

i want allow user send http request like:

/path/to/my/script/?gimme=my_stuff[alpha][2][delta] 

and have request return echo. similarly, if gimme=foxtrot, want return golf.

i can't pass off eval() right? security implications alone bad, can't imagine performance being either.

the syntax of request can change entirely, requirement allow users request arbitrary portions of server-side object.... just object, read-only.

is there safe/smart way this, or crazy?

martijn pieters put me on right track, there still work figure out how reduce() traverse various object types, i'll outline of here.

for case, my_stuff object bunch of different property types:

class alpha(object):     def __init__(self):         bravo = [1, 2, 3]         charlie = 7  class delta(object):     def __init__(self):         echo = [alpha(), alpha()]         foxtrot = {             "golf": "hotel"         } 

so simple reduce(dict.__getitem__, path, my_stuff) wasn't going job here. using start though, ended this:

def get_parsed_attribute(self, result, field_name):     try:         return reduce(self.smart_getattr, field_name.split("__"), result)     except (attributeerror, indexerror):         return none  # can assume either value missing, or                      # key doesn't exist.  either way, there's no harm.   @staticmethod def smart_getattr(obj, key):     if isinstance(obj, list):         return list.__getitem__(obj, int(key))     if isinstance(obj, dict):         return dict.__getitem__(obj, key)     return getattr(obj, key) 

this code figures out kind of object we're dealing , executes appropriate getter, when it's called reduce() same effect martijn suggested simple dictionary.


Comments

Popular posts from this blog

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -

python 3.x - Mapping specific letters onto a list of words -