I have written a small tool to generate a json file from sqlalchemy models files to automate the tedious procedure of writing all the sql raws in a json format. The script works, but there are few parts, see get_modules function, that can be improved. I would be glad to have a review of this code. Thanks
# -*- coding: utf-8 -*-
import os
import sys
import glob
PATH = sys.argv[1]
output_filename = 'en.json'
intro = ("""
{
"sidebar": {
"overview": "Overview",
},
"about": {
"title": "title"
},
"welcome": {
"title": "Welcome to the prototype app!"
},
""")
def get_fields(input_filename):
"""It returns all fields of a model in a list"""
fields = []
endpoint = None
with open(PATH+input_filename, 'r') as inputfile:
for line in inputfile:
if '__plural_name__' in line:
endpoint = line.split('=')[1].strip().replace("'","")
if '= Column' in line:
fields.append(line.split()[0])
return endpoint, fields
def get_modules():
"""It returns a list of all models"""
files = []
cwd = os.getcwd()
os.chdir(PATH)
files = glob.glob("*.py")
os.chdir(cwd)
return files
if __name__ == "__main__":
models = get_modules()
target = open(output_filename, 'w')
target.write(intro)
for m in models:
if m != '__init__.py':
end_name, attrs = get_fields(m)
target.write(' "{}": {{\n'.format(end_name))
target.write(' "title": "{}",\n'.format(end_name))
target.write(' "fields": {\n')
for a in attrs:
target.write(' "{}": "{}",\n'.format(a,a))
target.write(' }\n')
target.write(' },\n')
target.close()