usr bin env python coding utf-8 from __future__ import division print_

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/env python
# coding: utf-8
from __future__ import division, print_function, unicode_literals
import glob
from os.path import join
import yaml
from django.conf import settings
from django.db import models
YAML_DIR = getattr(settings, 'YAML_DIR', '../yml')
_str_to_field_class = {
'int': [models.IntegerField, {}],
'char': [models.CharField, {}],
'date': [models.DateTimeField, {'max_length': 80}],
}
def camel_case(name):
return str(''.join(x.capitalize() for x in name.split('_')))
def get_field_class(name):
return _str_to_field_class[name]
def create_model(name, title, fields):
attrs = {}
for field in fields:
field_class, field_attrs = get_field_class(field['type'])
attrs[field['id']] = field_class(field['title'],
**field_attrs)
class Meta:
verbose_name_plural = title
attrs.update({'__module__': __name__, 'Meta': Meta})
model = type(camel_case(name), (models.Model,), attrs)
# setattr(model, 'Meta', Meta)
# model.__module__ = 'main'
return model
def aggr_yamls():
response = {}
for filename in glob.glob1(YAML_DIR, '*.y?ml'):
full_path = join(YAML_DIR, filename)
response.update(yaml.load(open(full_path, 'r')))
return response
def generate_models():
response = []
for key, value in aggr_yamls().items():
title = value.get('title', '')
response.append(create_model(key, title, value['fields']))
return response