-
Notifications
You must be signed in to change notification settings - Fork 2
/
djangorm.py
80 lines (71 loc) · 2.54 KB
/
djangorm.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/bin/python3
import os
import sys
import inspect
from django.conf import settings
from django.apps import apps
from django.core.management import execute_from_command_line
from django.db.models import ManyToManyField
from django.db import connections
class DjangORM:
def __init__(self, module_name, database=None, module_path='.'):
if database is None:
module_path = os.path.join(os.path.join(os.path.dirname(sys.argv[0]), module_path), module_name)
if os.path.exists(module_path) is False:
os.makedirs(module_path)
database = {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(module_path, 'db.sqlite3')
}
if not isinstance(module_name, str):
raise ValueError
if not isinstance(database, dict):
raise ValueError
self.module_name = module_name
self.database = database
self.__configured__ = False
@staticmethod
def close_old_connections():
for conn in connections.all():
conn.close_if_unusable_or_obsolete()
def configure(self):
if self.__configured__:
return
configuration = {
'INSTALLED_APPS': [
self.module_name
],
'DATABASES': {
'default': self.database
}
}
settings.configure(**configuration)
apps.populate(settings.INSTALLED_APPS)
self.__configured__ = True
def migrate(self):
if self.__configured__ is False:
self.configure()
execute_from_command_line(['', 'makemigrations', self.module_name])
execute_from_command_line(['', 'migrate', self.module_name])
def check_models(self, models):
models_members = inspect.getmembers(models, inspect.isclass)
for i in models_members:
models_class = i[1]
try:
models_class.objects.filter()[0]
except IndexError:
continue
self.close_old_connections()
@staticmethod
def object_to_dict(instance):
opts = instance._meta
data = {}
for f in opts.concrete_fields + opts.many_to_many:
if isinstance(f, ManyToManyField):
if instance.pk is None:
data[f.name] = []
else:
data[f.name] = list(f.value_from_object(instance).values_list('pk', flat=True))
else:
data[f.name] = f.value_from_object(instance)
return data