Created
November 13, 2016 22:54
-
-
Save smetj/0fc29f2ef51486f4326d023dc4546588 to your computer and use it in GitHub Desktop.
Input validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# | |
import json | |
from jsonschema import validate | |
class Greeting(object): | |
SCHEMA = { | |
"type": "object", | |
"properties": { | |
"greeting": { | |
"enum": [ | |
"Good morning", | |
"Good afternoon", | |
"Good evening", | |
"Good night" | |
], | |
"type": "string" | |
}, | |
"name": { | |
"type": "string" | |
}, | |
"title": { | |
"type": "string" | |
} | |
}, | |
"additionalProperties": False, | |
"required": [ | |
"greeting", | |
"title", | |
"name" | |
] | |
} | |
def __init__(self, data): | |
self.text = data | |
self.json = self._processResponse(data) | |
def _processResponse(self, data): | |
j = json.loads(data) | |
validate(j, self.SCHEMA) | |
return j | |
def __str__(self): | |
return "<Greeting(greeting='%s', title='%s', name='%s')>" % (self.json["greeting"], self.json["title"], self.json["name"]) | |
def main(): | |
print(Greeting(r'{"greeting": "Good morning", "title": "Mr.", "name": "Bean"}')) | |
print Greeting.SCHEMA | |
if __name__ == "__main__": | |
main() |
Author
smetj
commented
Nov 13, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment