Python convert String to Tuple for REST API
I'm trying to build a REST API using django-piston and in the library, I can specify the fields to display using a tuples.
fields = ('id', 'title', ('author', 'username',),)
Hence, I would like to allow the developer to request the data format via GET operation such as:
http://localhost/api/users?attr=(id,title,(author,username,),)
I've read that I can use eval() to convert string to tuple. However, I met with two blockers.
- Is there an easy way to add quotes to the param name such that it become "('id','title', ('author','username'))"?
- Is eval safe to do it? I read that I can removed the builtin functions via this: eval("('id','title',('author','username',),)", {'_builtins_':[]}, {})
For a little context as to why I'm allowing developer开发者_如何学C to specify the dataset, I'm following the advice from LinkedIn on how to build REST API.
Here's the link: http://blog.linkedin.com/2009/07/08/brandon-duncan-java-one-building-consistent-restful-apis-in-a-high-performance-environment/
Any help is really appreciated.
Cheers, Mickey
You didn't specify the Python version you are using, but here's a solution that works in Python 2.6 and doesn't use eval.
import ast
def parse_params(s):
root = ast.parse(s)
expr = root.body[0]
return process_node(expr.value)
def process_node(node):
if isinstance(node, ast.Tuple):
return tuple(map(process_node, node.elts))
elif isinstance(node, ast.Name):
return node.id
else:
raise ValueError("unsupported node type %r" % node)
>>> parse_params('(id,title,(author,username,),)')
('id', 'title', ('author', 'username'))
I would just use regular string methods for parsing, and whatever syntax you find suitable. In my opinion, it's totally uncool to expose your inner gears like that.
精彩评论