Created
February 2, 2016 13:34
-
-
Save webjunkie/ebe0fa52b5fb7fe7715f to your computer and use it in GitHub Desktop.
Convert swagger to django model definition
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
import json | |
with open("swagger.json", "r") as f: | |
data = json.load(f) | |
def print_properties(value, pad=""): | |
properties = value.get('properties', {}) | |
required = value.get('required', []) | |
for prop, prop_val in properties.items(): | |
null = True | |
if prop == "type": | |
prop = "%s_type" % entity.lower() | |
s = "%s %s = models." % (pad, prop) | |
if prop_val.get('format') == "date-time": | |
s += "DateTimeField(" | |
elif prop_val.get('type') == "number": | |
s += "DecimalField(" | |
elif prop_val.get('type') == "integer": | |
s += "IntegerField(" | |
elif prop_val.get('type') == "boolean": | |
s += "BooleanField(" | |
null = False | |
elif prop_val.get('type') == "array": | |
s += "ManyToManyField(?, )" | |
elif prop_val.get('type') == "object": | |
s += "ForeignKey(?, " | |
if prop_val.get('properties'): | |
print_properties(prop_val, pad=pad+" ") | |
elif prop_val.get('$ref'): | |
s += "ForeignKey(%s, " % prop_val.get('$ref').replace("#/definitions/", "") | |
else: | |
s += "CharField(max_length=255, " | |
null = False | |
try: | |
for i in prop_val.get("items", {}).get("allOf", []): | |
if i.get('properties'): | |
print_properties(i, pad=pad+" ") | |
except AttributeError: | |
pass | |
if prop not in required: | |
if null: | |
s += "null=True, " | |
s += "blank=True" | |
s += ")" | |
print s.replace(", )", ")") | |
for entity, value in data['definitions'].items(): | |
print "class %s(models.Model):" % entity | |
print_properties(value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple conversion of a swagger definition to Django model, in case one needs to store the data in the same way.
Still has some issues with nested elements, but already saves some work writing fields by hand.