-
Notifications
You must be signed in to change notification settings - Fork 236
/
Copy pathh_django.py
262 lines (201 loc) · 7.49 KB
/
h_django.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# -*- encoding: utf-8 -*-
"""
Copyright (c) App-Generator.dev | AppSeed.us
"""
import random, string, time, sys
from datetime import datetime
import django
from django.utils import timezone
from django.contrib.auth import get_user_model
from .common import *
from .h_files import *
from .h_util import *
from .h_shell import *
from .h_code_parser import *
def get_django():
os.environ.setdefault("DJANGO_SETTINGS_MODULE", DIR_DJ_CONFIG + ".settings")
from collections import OrderedDict
from django.apps import apps
from django.conf import settings
from django.core import management
# Needs a single init
if not apps.ready:
apps.app_configs = OrderedDict()
apps.ready = False
apps.populate(settings.INSTALLED_APPS)
return apps
def check_db_conn():
apps = get_django()
from django.db import connection
from django.db.utils import OperationalError
db_conn = None
while not db_conn:
try:
connection.ensure_connection()
db_conn = True
except OperationalError:
print('Database unavailable, waiting 1 second...')
time.sleep(1)
print('Connecton OK')
def get_apps():
retVal = []
apps = get_django()
for app in apps.get_app_configs():
retVal.append( app.name )
return retVal
def get_models(aApp):
retVal = []
apps = get_django()
models = apps.get_app_config( aApp ).get_models()
for m in models:
retVal.append( m )
return retVal
def get_models_name(aApp):
retVal = []
models = get_models( aApp )
for m in models:
retVal.append( m.__name__ )
return retVal
def get_model_by_name(aApp, aModelname):
models = get_models( aApp )
for m in models:
if m.__name__ == aModelname:
return m
return None
def get_model_fields(aModelClass):
retVal = []
for f in aModelClass._meta.fields:
retVal.append( f )
return retVal
def get_model_fk(aModelClass):
retVal = {}
for f in aModelClass._meta.fields:
if type( f ) is django.db.models.fields.related.ForeignKey:
#print( ' FK: ' + )
f_class = f.related_model.__module__ + '.' + f.related_model.__name__
retVal[ f.name ] = f_class
return retVal
def get_model_fk_values(aModelClass):
retVal = {}
for f in aModelClass._meta.fields:
if type( f ) is django.db.models.fields.related.ForeignKey:
f_class = f.related_model.__module__ + '.' + f.related_model.__name__
retVal[ f.name ] = list( name_to_class( f_class ).objects.all() )
return retVal
# v = verbose
def get_model_fields_v(aModelClass):
retVal = {}
for f in aModelClass._meta.fields:
retVal[ f.name ] = f.__class__.__name__
return retVal
def check_model_migration( aModelClass ):
from django.db.utils import OperationalError
try:
aModelClass.objects.last()
return True
except OperationalError:
return False
def extract_class_code(aFilePath, aClassName):
file_content = file_load( aFilePath )
if not file_content:
print(' > ERR loading file: ' + aFilePath)
return None
manipulator = PythonFileClassManipulator(aFilePath)
return manipulator.extract_class_code(aClassName)
def add_model(aAppName, aModelName):
target_file = os.path.join(DIR_ROOT, aAppName, 'models.py')
if aAppName not in get_apps():
print(' > ERR: App not registered: ' + aAppName)
print(' |- Expected on of: ' + str( get_apps() ) )
return
if aModelName in get_models_name(aAppName):
print(' > ERR: ' + aModelName + ' already defined in ' + aAppName)
return
else:
target_file_c = file_load( target_file )
model_class = f"class {aModelName}(models.Model)"
if model_class in target_file_c:
print(' > ERR: ' + aModelName + ' already defined in ' + aAppName)
return
model_code = file_load( os.path.join(DIR_ROOT, 'templates', 'generator', 'model.tmpl') )
if not model_code:
print(' > ERR loading template ')
return
model_code = model_code.replace('__MODEL_NAME__', aModelName)
file_append( target_file, model_code )
# format code
exec_format_code( target_file )
# Check dry-run status
exec_migration()
def add_model_field(aAppName, aModelName, aFieldName, aFieldType, **kwargs):
file_path = os.path.join( aAppName, 'models.py' )
# Check Input
if aAppName not in get_apps():
print(' > ERR: App not registered: ' + aAppName)
print(' |- Expected on of: ' + str( get_apps() ) )
return
file_c = extract_class_code( file_path, aModelName )
if not file_c:
print(' > ERR: Model [' +aModelName+ '] not found in app: ' + aAppName)
return
str1 = aFieldName + '='
str2 = aFieldName + ' ='
str3 = aFieldName + ' = '
if str1 in file_c or str2 in file_c or str3 in file_c:
print(' > ERR: Field [' +aFieldName+ '] already in model ' + aModelName)
return
aFieldTypeDB = str_to_db_type( aFieldType )
aFieldProps = {}
aFieldProps['blank'] = True
aFieldProps['null'] = True
aFieldClass = None
if DbField.CHAR_FIELD == aFieldTypeDB:
aFieldProps['max_length']=255
if DbField.NA == aFieldTypeDB:
# We can have class type
aFieldClass = name_to_class(aFieldType)
if not aFieldClass:
print(' > ERR: Unsupported aFieldType [' +aFieldType+ '] ')
return
aFieldTypeDB = DbField.FK_FIELD
kwargs = aFieldProps
manipulator = PythonFileClassManipulator(file_path)
model_code = manipulator.extract_class_code(aModelName)
model_code_upd = None
if DbField.FK_FIELD == aFieldTypeDB:
model_code_upd = add_fk_to_django_model( model_code, field_name=aFieldName, field_type=aFieldTypeDB, related_model=aFieldClass.__name__, on_delete="models.CASCADE", position=1, **kwargs)
else:
model_code_upd = add_field_to_django_model( model_code, field_name=aFieldName, field_type=aFieldTypeDB, position=1, **kwargs)
manipulator.replace_class(aModelName, model_code_upd )
manipulator.save_modified_file()
# format code
exec_format_code( file_path )
# Check dry-run status
exec_migration()
def del_model_field(aAppName, aModelName, aFieldName):
file_path = os.path.join( aAppName, 'models.py' )
# Check Input
if aAppName not in get_apps():
print(' > ERR: App not registered: ' + aAppName)
print(' |- Expected on of: ' + str( get_apps() ) )
return
file_c = extract_class_code( file_path, aModelName )
if not file_c:
print(' > ERR: Model [' +aModelName+ '] not found in app: ' + aAppName)
return
manipulator = PythonFileClassManipulator(file_path)
model_code = manipulator.extract_class_code(aModelName)
model_code_upd = remove_field_from_django_model(model_code, aFieldName)
manipulator.replace_class(aModelName, model_code_upd )
manipulator.save_modified_file()
# format code
exec_format_code( file_path )
# Check dry-run status
exec_migration()
def get_users():
return get_user_model().objects.all()
def get_user(aInput):
user = get_users().filter(username=aInput).first()
if not user:
user = get_users().filter(email=aInput).first()
return user