Validate object values against yaml configuration

时间:2017-08-04 12:04:43

标签: python configuration yaml

I have an application where a nested Python dictionary is created based on a JSON document that I get as a response from an API. Example:

colleagues = [
{  "name": "John",
   "skills": ["python", "java", "scala"],
   "job": "developer"
},
{  "name": "George",
   "skills": ["c", "go", "nodejs"],
   "job": "developer"
}]

This dictionary can have many more nested levels. What I want to do is let the user define their own arbitrary conditions (e.g. in order to find colleagues that have "python" among their skills, or whose name is "John") in a YAML configuration file, which I will use to check against the Python dictionary.

I thought about letting them configure that in the following manner in the YAML file, but this would require using exec(), which I want to avoid for security reasons:

constraints:
    - "python" in colleagues[x]["skills"]
    - colleagues[x]["name"] == "John"

What other options are there for such a problem, so that the user can specify their own constraints for the dictionary values? Again, the dictionary above is just an example. The actual one is much larger in size and nesting levels.

1 个答案:

答案 0 :(得分:1)

You could use a Lucene query parser to convert queries like "skill:python" and "name:John" to executable predicate functions, and then filter your list of colleagues using those predicates. Googling for "python lucene parser" will turn up several parsing options.