forked from femmerling/EmeraldBox
/
box.py
executable file
·692 lines (574 loc) · 31.2 KB
/
box.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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
#! box/bin/python
import imp
import sys
import os.path
from subprocess import call,Popen,PIPE
import platform
import re
import logging
from migrate.versioning import api
from app import db
from config import BASEDIR, SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, SERVER_PORT, WHITE_SPACE
spc = "\t"
if WHITE_SPACE == "space":
spc = " "
# This variable will be used to check the valid data types enterred by the user in box.py -n command.
valid_data_types = [
'boolean', 'date', 'time', 'datetime', 'enum', 'interval', 'pickletype', 'schematype',
'numeric', 'float', 'biginteger', 'smallinteger', 'smallint', 'string', 'bigint','int','integer',
'text', 'unicode', 'unicodetext', 'binary', 'largebinary', 'blob'
]
def help():
# This lists the commands used by the db_tools.py.
print '\nThe general usage pattern of the tool is python box.py [options] [extra parameters]\n'
print 'The following are the available options:\n'
print ' --initiate or -i : Generates a new controller handler. You should specify a controller name and the name should not be a number.'
print '\t\t\t The pattern is python box.py -i [controller name]'
print ' --create or -c : Create the database for the first usage. Only use this if you want to create the database for the first time'
print ' --migrate or -m : Create the migration script for migration process'
print ' --upgrade or -u : Upgrade the database to the latest migration version'
print ' --downgrade or -d : Downgrade the database to the previous migration version.'
print '\t\t\t To downgrade to a specific version use python box.py -d [version number]'
print '--version or -v\t\t : Check current database version.'
print ' --new or -n : Create new data model.'
print '\t\t\t The pattern is box.py -n [model name] [<field name>:<field type>--<field length (if applicable. otherwise, default will be used)>]'
print '\t\t\t For more documentation please see http://docs.sqlalchemy.org/en/rel_0_7/core/types.html#types-generic'
print ' --add or -a : Install a new python package.'
print '\t\t\t The pattern is python box.py -a [package name]'
print ' --help or -h : Display the help file'
print ' --serve or -s : Run The Tornado Web Server'
print ' --gserve or -g : Run The Gunicorn Web Server. You can add your own gunicorn options aside from bind address and port'
print ' --testrun or -t : Run The Development Server'
print ''
def db_create():
# This creates the new database.
db.create_all()
# If no repo existed, the creation will prepare for the first migration.
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
print '\nDatabase creation completed\n'
else:
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO))
def db_migrate():
# This is used for database migration. Newly created database should go through this as well.
migration = SQLALCHEMY_MIGRATE_REPO + '/versions/%03d_migration.py' % (api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) + 1)
tmp_module = imp.new_module('old_model')
old_model = api.create_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
exec old_model in tmp_module.__dict__
script = api.make_update_script_for_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, tmp_module.meta, db.metadata)
open(migration, "wt").write(script)
api.upgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
print 'New migration saved as ' + migration
print 'Current database version: ' + str(api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)) + '\n'
def db_upgrade():
# This is used for database migration upgrade.
api.upgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
print 'Database upgrade completed!'
print 'Current database version is: ' + str(api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO))
def db_downgrade(version=None):
# This is used to downgrade the database schema to a certain version or to one version before.
# If you know exactly the version you wish to use then you can directly downgrade to that version.
if not version:
current_version = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
downgrade_version = current_version - 1
else:
downgrade_version = version
api.downgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, downgrade_version)
print 'Database downgrade completed!'
print 'Current database version: ' + str(api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO))
def add_model(model_name, model_components):
# This is used to add model to the model file.
# Get the current model file and open it for writing.
model_path = os.path.join(BASEDIR, "app/models/" + model_name.lower() + ".py")
init_path = os.path.join(BASEDIR, "app/models/__init__.py")
model_file = open(model_path, 'w')
# Write the class definition.
model_file.write('from app import db\n\n')
model_file.write('class ' + model_name.title() + '(db.Model):\n')
model_file.write(spc+'id = db.Column(db.Integer, primary_key=True)\n')
## Add the model fields.
### First check for the data types and standardize it.
for component in model_components:
in_type = component['field_property'][0].lower()
### The database field type based on http://docs.sqlalchemy.org/en/rel_0_7/core/types.html#types-generic.
if in_type == 'biginteger' or in_type == 'bigint':
data_type = 'BigInteger'
elif in_type=='int' or in_type=='integer':
data_type = 'Integer'
elif in_type == 'boolean':
data_type = 'Boolean'
elif in_type == 'date':
data_type = 'Date'
elif in_type == 'datetime':
data_type = 'DateTime'
elif in_type == 'enum':
data_type = 'Enum'
elif in_type == 'float':
data_type = 'Float'
elif in_type == 'interval':
data_type = 'Interval'
elif in_type == 'largebinary':
data_type = 'LargeBinary'
elif in_type == 'numeric':
data_type = 'Numeric'
elif in_type == 'pickletype':
data_type = 'PickleType'
elif in_type == 'schematype':
data_type = 'SchemaType'
elif in_type == 'smallinteger' or in_type == 'smallint':
data_type = 'SmallInteger'
elif in_type == 'string':
data_type = 'String'
elif in_type == 'text':
data_type = 'Text'
elif in_type == 'time':
data_type = 'Time'
elif in_type == 'unicode':
data_type = 'Unicode'
elif in_type == 'unicodetext':
data_type = 'UnicodeText'
elif in_type == 'binary':
data_type = 'Binary'
elif in_type == 'blob':
data_type = 'BLOB'
else:
### If the data type did not match any of the existing data types, display error message and quit the program.
print 'Data type ' + component['field_property'][0] + ' not found. Please refer to SQLAlchemy documentation for valid data types.'
sys.exit()
### If it matches write the model fields into the model files.
if len(component['field_property']) == 2:
model_file.write(spc + component['field_name'].lower() + ' = db.Column(db.' + data_type + '(' + component['field_property'][1] + '))\n')
else:
model_file.write(spc + component['field_name'].lower() + ' = db.Column(db.' + data_type + ')\n')
## Create the class method for data transfer object (dto) for JSON representation.
model_file.write('\n')
model_file.write(spc + '# data transfer object to form JSON\n')
model_file.write(spc + 'def dto(self):\n')
model_file.write(spc + spc + 'return dict(\n')
### Add the json component for all fields.
mod_counter = 1
model_file.write(spc+spc+spc+'id = self.id,\n')
max_mod_index = len(model_components)
for component in model_components:
if mod_counter != max_mod_index:
model_file.write(spc + spc + spc + component['field_name'].lower() + ' = self.' + component['field_name'].lower() + ',\n')
else:
model_file.write(spc + spc + spc + component['field_name'].lower() + ' = self.' + component['field_name'].lower() + ')\n')
mod_counter = mod_counter + 1
model_file.close()
init_file = open(init_path, 'a')
init_file.write("from "+ model_name.lower() + " import " + model_name.title()+"\n")
init_file.close()
print '\n...........\n'
#add the CRUD controllers
generate_controller(model_name, model_components)
generate_index_template(model_name, model_components)
generate_controller_template(model_name, model_components)
generate_edit_template(model_name, model_components)
generate_view_template(model_name, model_components)
# perform the database creation and migration.
# this will be based on the state of the database.
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
db_create()
db_migrate()
print "Please run box.py -m to complete the migration process"
def generate_controller(model_name, model_components):
model_name = model_name.lower()
db_model_name = model_name.title()
mod_counter = 1
max_mod_index = len(model_components)
controller_path = os.path.join(BASEDIR, 'app/controllers/'+model_name+'.py')
controller_file = open(controller_path,'w')
controller_file.write("from flask import Blueprint\n")
controller_file.write("from flask import render_template\n")
controller_file.write("from flask import json\n")
controller_file.write("from flask import session\n")
controller_file.write("from flask import url_for\n")
controller_file.write("from flask import redirect\n")
controller_file.write("from flask import request\n")
controller_file.write("from flask import abort\n")
controller_file.write("from flask import Response\n\n")
controller_file.write("from app import db\n\n")
# import related models
controller_file.write("from app.models import " + db_model_name +"\n\n")
# create blueprint
controller_file.write(model_name+"_view = Blueprint('"+model_name+"_view', __name__)\n\n")
controller_file.write("########### " + model_name + " REST controller ###########\n\n")
controller_file.write("@"+model_name+"_view.route('/" + model_name + "/',methods=['GET','POST'],defaults={'id':None})\n")
controller_file.write("@"+model_name+"_view.route('/" + model_name + "/<id>',methods=['GET','PUT','DELETE'])\n")
controller_file.write("def " + model_name + "_controller(id):\n")
for component in model_components:
controller_file.write(spc + component['field_name'].lower() + " = request.values.get('" + component['field_name'].lower() + "')\n")
controller_file.write("\n"+ spc +"if id:\n")
controller_file.write(spc + spc + "if request.method == 'GET':\n")
controller_file.write(spc + spc + spc + model_name+" = "+model_name.title()+".query.get(id)\n")
controller_file.write(spc + spc + spc+ "if "+model_name+":\n")
controller_file.write(spc + spc + spc + spc + model_name+" = "+model_name+".dto()\n")
controller_file.write(spc + spc + spc + "if request.values.get('json'):\n")
controller_file.write(spc + spc + spc + spc +"return json.dumps(dict("+model_name+"="+model_name+"))\n")
controller_file.write(spc + spc + spc + "else:\n")
controller_file.write(spc + spc + spc + spc + "return render_template('"+model_name+"_view.html', "+model_name+" = "+model_name+")\n")
controller_file.write(spc + spc + "elif request.method == 'PUT':\n")
controller_file.write(spc + spc + spc + model_name + "_item = " + model_name.title() + ".query.get(id)\n")
for component in model_components:
controller_file.write(spc + spc + spc + model_name + "_item." + component['field_name'].lower() + " = " + component['field_name'].lower() + "\n")
controller_file.write(spc + spc + spc + "db.session.add(" + model_name + "_item)\n")
controller_file.write(spc + spc + spc + "db.session.commit()\n")
controller_file.write(spc + spc + spc + "return 'updated'\n")
controller_file.write(spc + spc + "elif request.method == 'DELETE':\n")
controller_file.write(spc + spc + spc + model_name + "_item = " + model_name.title() + ".query.get(id)\n")
controller_file.write(spc + spc + spc + "db.session.delete(" + model_name + "_item)\n")
controller_file.write(spc + spc + spc + "db.session.commit()\n")
controller_file.write(spc + spc + spc + "return 'deleted'\n")
controller_file.write(spc + spc + "else:\n")
controller_file.write(spc + spc + spc +"return 'Method Not Allowed'\n")
controller_file.write(spc + "else:\n")
controller_file.write(spc + spc + "if request.method == 'GET':\n")
controller_file.write(spc + spc + spc + model_name + "_list = "+model_name.title()+".query.all()\n")
controller_file.write(spc + spc + spc + "if " + model_name + "_list:\n")
controller_file.write(spc + spc + spc + spc + "entries = [" + model_name + ".dto() for " + model_name + " in " + model_name + "_list]\n")
controller_file.write(spc + spc + spc + "else:\n")
controller_file.write(spc + spc + spc + spc + "entries=None\n")
controller_file.write(spc + spc + spc + "if request.values.get('json'):\n")
controller_file.write(spc + spc + spc + spc + "return json.dumps(dict("+model_name+"=entries))\n")
controller_file.write(spc + spc + spc + "else:\n")
controller_file.write(spc + spc + spc + spc + "return render_template('" + model_name + ".html'," + model_name + "_entries = entries, title = \"" + model_name.title() + " List\")\n")
controller_file.write(spc + spc + "elif request.method == 'POST':\n")
controller_file.write(spc + spc + spc + "new_"+model_name+" = "+model_name.title()+"(\n")
for component in model_components:
if mod_counter != max_mod_index:
controller_file.write(spc + spc + spc + spc + spc + spc + spc + component['field_name'].lower() + ' = ' + component['field_name'].lower() + ',\n')
else:
controller_file.write(spc + spc + spc + spc + spc + spc + spc + component['field_name'].lower() + ' = ' + component['field_name'].lower() + '\n')
mod_counter = mod_counter + 1
controller_file.write(spc + spc + spc + spc + spc + spc + spc + ")\n\n")
controller_file.write(spc + spc + spc + "db.session.add(new_" + model_name + ")\n")
controller_file.write(spc + spc + spc + "db.session.commit()\n")
controller_file.write(spc + spc + spc + "if request.values.get('json'):\n")
controller_file.write(spc + spc + spc + spc + "url = '/"+model_name+"/json=true'\n")
controller_file.write(spc + spc + spc + "else:\n")
controller_file.write(spc + spc + spc + spc + "url = '/"+model_name+"/'\n")
controller_file.write(spc + spc + spc + "return redirect(url)\n")
controller_file.write(spc + spc + "else:\n")
controller_file.write(spc + spc + spc + "return 'Method Not Allowed'\n\n")
controller_file.close()
main_path = os.path.join(BASEDIR, 'app/main.py')
read_main_file = open(main_path, 'r')
original_lines = read_main_file.readlines()
## import the blueprint file
original_lines[2] = original_lines[2].strip()
original_lines[2] = original_lines[2] + ', ' + model_name + '_view\n'
main_file = open(main_path, 'w')
for lines in original_lines:
main_file.write(lines)
main_file.close()
main_file = open(main_path,'a')
main_file.write("\napp.register_blueprint(" + model_name + "_view)")
main_file.close()
init_path = os.path.join(BASEDIR, 'app/controllers/__init__.py')
init_file = open(init_path, 'a')
init_file.write("\nfrom "+ model_name + " import "+model_name+ "_view")
init_file.close()
print "REST controller generated"
def generate_index_template(model_name, model_components):
model_name = model_name.lower()
template_path = os.path.join(BASEDIR, 'app/templates/' + model_name + '.html')
template_file = open(template_path, 'w')
template_file.write("{% extends \"base.html\" %}\n")
template_file.write("{% block content %}\n")
template_file.write("\t\t<h1>List of " + model_name.title() + " Entries.</h1>\n")
template_file.write("\t\t<table id=\"list-view\">\n")
template_file.write("\t\t\t<thead>\n")
template_file.write("\t\t\t\t<tr>\n")
template_file.write("\t\t\t\t\t<td><b>ID</td>\n")
for component in model_components:
template_file.write("\t\t\t\t\t<td><b>" + component['field_name'].title() + "</b></td>\n")
template_file.write("\t\t\t\t\t<td><b> </td>\n")
template_file.write("\t\t\t\t\t<td><b> </td>\n")
template_file.write("\t\t\t\t</tr>\n")
template_file.write("\t\t\t</thead>\n")
template_file.write("\t\t\t{% if " + model_name + "_entries %}\n")
template_file.write("\t\t\t<tbody>\n")
template_file.write("\t\t\t{% for entry in " + model_name + "_entries %}\n")
template_file.write("\t\t\t\t<tr>\n")
template_file.write("\t\t\t\t\t<td><a href=\"/"+model_name+"/{{ entry.id }}\">{{ entry.id }}</a></td>\n")
for component in model_components:
template_file.write("\t\t\t\t\t<td>{{ entry." + component['field_name'] + " }}</td>\n")
template_file.write('\t\t\t\t\t<td><a href="/' + model_name + '/edit/{{ entry.id }}">Edit</a></td>\n')
template_file.write('\t\t\t\t\t<td><a id="delete-link" data-callback="/' + model_name + '/" data-url="/' + model_name + '/{{ entry.id }}">Delete</a></td>\n')
template_file.write("\t\t\t\t</tr>\n")
template_file.write("\t\t\t{% endfor %}\n")
template_file.write("\t\t\t</tbody>\n")
template_file.write("\t\t</table>\n")
template_file.write("\t\t\t{% else %}\n")
template_file.write("\t\t</table>\n")
template_file.write("\t\tYou have no entries yet\n")
template_file.write("\t\t\t{% endif %}\n")
template_file.write('\t\t\t<br/><br/><b><a id="actions" href="/' + model_name + '/add">Add new entry</a></b>\n')
template_file.write("{% endblock %}\n")
print "index template generated"
def generate_view_template(model_name, model_components):
model_name = model_name.lower()
template_path = os.path.join(BASEDIR, 'app/templates/' + model_name + '_view.html')
template_file = open(template_path, 'w')
template_file.write("{% extends \"base.html\" %}\n")
template_file.write("{% block content %}\n")
template_file.write("\t\t<h1>View " + model_name.title() + " single entry.</h1>\n")
template_file.write("\t\t<table>\n")
for component in model_components:
template_file.write("\t\t\t\t<tr>\n")
template_file.write("\t\t\t\t\t<td>" + component['field_name'].title() + ":</td>\n")
template_file.write("\t\t\t\t\t<td>{{ " + model_name + "." + component['field_name'].lower() + " }}</td>\n")
template_file.write("\t\t\t\t</tr>\n")
template_file.write("\t\t</table>\n")
template_file.write("{% endblock %}")
print 'view template generated'
def generate_edit_template(model_name, model_components):
model_name = model_name.lower()
controller_path = os.path.join(BASEDIR, 'app/controllers/'+model_name+'.py')
template_path = os.path.join(BASEDIR, 'app/templates/' + model_name + '_edit.html')
controller_file = open(controller_path, 'a')
controller_file.write("@"+model_name+"_view.route('/" + model_name + "/edit/<id>')\n")
controller_file.write("def " + model_name + "_edit_controller(id):\n")
controller_file.write(spc + "#this is the controller to edit model entries\n")
controller_file.write(spc + model_name + "_item = " + model_name.title() + ".query.get(id)\n")
controller_file.write(spc + "return render_template('" + model_name + "_edit.html', " + model_name + "_item = " + model_name + "_item, title = \"Edit Entries\")\n\n")
template_file = open(template_path, 'w')
template_file.write("{% extends \"base.html\" %}\n")
template_file.write("{% block content %}\n")
template_file.write("\t\t<h1>Edit " + model_name.title() + " Entries.</h1>\n")
template_file.write("\t\t<form id=\"edit-form\" name=\"" + model_name + "_add\" method=\"put\" action=\"/" + model_name + "/{{ " + model_name + "_item.id }}\">\n")
template_file.write("\t\t<input type=\"hidden\" id=\"url\" value=\"/"+model_name+"/{{ " + model_name + "_item.id }}\">\n")
template_file.write("\t\t<table>\n")
for component in model_components:
template_file.write("\t\t\t\t<tr>\n")
template_file.write("\t\t\t\t\t<td>" + component['field_name'].title() + ":</td>\n")
template_file.write("\t\t\t\t\t<td><input type=\"text\" name=\"" + component['field_name'].lower() + "\" value=\"{{ " + model_name + "_item." + component['field_name'].lower() + " }}\"/></td>\n")
template_file.write("\t\t\t\t</tr>\n")
template_file.write("\t\t\t\t<tr>\n")
template_file.write("\t\t\t\t\t<td><input id=\"submit-put\" type=\"submit\" name=\"submit\" value=\"Edit Entry\"/></td>\n")
template_file.write("\t\t\t\t\t<td> </td>\n")
template_file.write("\t\t\t\t</tr>\n")
template_file.write("\t\t</table>\n")
template_file.write("\t\t</form>\n")
template_file.write("{% endblock %}")
print 'Entries edit and update form controller added'
def generate_controller_template(model_name, model_components):
model_name = model_name.lower()
controller_path = os.path.join(BASEDIR, 'app/controllers/'+model_name+'.py')
template_path = os.path.join(BASEDIR, 'app/templates/' + model_name + '_add.html')
controller_file = open(controller_path, 'a')
controller_file.write("@"+model_name+"_view.route('/" + model_name + "/add/')\n")
controller_file.write("def " + model_name + "_add_controller():\n")
controller_file.write(spc + "#this is the controller to add new model entries\n")
controller_file.write(spc + "return render_template('" + model_name + "_add.html', title = \"Add New Entry\")\n\n")
template_file = open(template_path, 'w')
template_file.write("{% extends \"base.html\" %}\n")
template_file.write("{% block content %}\n")
template_file.write("\t\t<h1>Add new " + model_name.title() + " Entries.</h1>\n")
template_file.write("\t\t<form name=\"" + model_name + "_add\" method=\"post\" action=\"/" + model_name + "/\">\n")
template_file.write("\t\t<table>\n")
for component in model_components:
template_file.write("\t\t\t\t<tr>\n")
template_file.write("\t\t\t\t\t<td>" + component['field_name'].title() + ":</td>\n")
template_file.write("\t\t\t\t\t<td><input type=\"text\" name=\"" + component['field_name'].lower() + "\"/></td>\n")
template_file.write("\t\t\t\t</tr>\n")
template_file.write("\t\t\t\t<tr>\n")
template_file.write("\t\t\t\t\t<td><input type=\"submit\" name=\"submit\" value=\"Add Entry\"/></td>\n")
template_file.write("\t\t\t\t\t<td> </td>\n")
template_file.write("\t\t\t\t</tr>\n")
template_file.write("\t\t</table>\n")
template_file.write("\t\t</form>\n")
template_file.write("{% endblock %}")
print 'Data add form controller generated'
def add_controller(controller_name):
controller_name = controller_name.lower()
controller_name = controller_name.replace(' ', '_')
controller_name = controller_name.replace('\'', '_')
controller_name = controller_name.replace('.', '_')
controller_name = controller_name.replace(',', '_')
controller_path = os.path.join(BASEDIR, "app/controllers/" + controller_name + ".py")
view_path = os.path.join(BASEDIR, "app/templates/" + controller_name + ".html")
controller_file = open(controller_path, 'w')
controller_file.write("from flask import Blueprint\n")
controller_file.write("from flask import render_template\n")
controller_file.write("from flask import json\n")
controller_file.write("from flask import session\n")
controller_file.write("from flask import url_for\n")
controller_file.write("from flask import redirect\n")
controller_file.write("from flask import request\n")
controller_file.write("from flask import abort\n")
controller_file.write("from flask import Response\n\n")
controller_file.write("from app import db\n\n")
controller_file.write(controller_name + "_view = Blueprint('" + controller_name + "_view', __name__)\n\n")
controller_file.write("@" + controller_name + "_view.route('/" + controller_name + "/') #Link\n")
controller_file.write("def " + controller_name + "_control():\n")
controller_file.write("\t# add your controller here\n")
controller_file.write("\treturn render_template('" + controller_name + ".html')\n")
controller_file.close()
main_path = os.path.join(BASEDIR, 'app/main.py')
read_main_file = open(main_path, 'r')
original_lines = read_main_file.readlines()
## import the blueprint file
original_lines[2] = original_lines[2].strip()
original_lines[2] = original_lines[2] + ', ' + controller_name + '_view\n'
main_path = os.path.join(BASEDIR, 'app/main.py')
main_file = open(main_path, 'w')
for lines in original_lines:
main_file.write(lines)
main_file.close()
main_file = open(main_path,'a')
main_file.write("\napp.register_blueprint(" + controller_name + "_view)")
main_file.close()
init_path = os.path.join(BASEDIR, 'app/controllers/__init__.py')
init_file = open(init_path, 'a')
init_file.write("\nfrom "+ controller_name + " import " + controller_name + "_view")
init_file.close()
print '\nController generated\n'
view_file = open(view_path, 'a')
view_file.write("{% extends \"base.html\" %}\n")
view_file.write("{% block content %}\n")
view_file.write('\t\t<h1>The ' + controller_name.lower() + ' view.</h1>\n')
view_file.write('\t\t<p>You can change this view in ' + view_path + '</p>\n')
view_file.write("{% endblock %}")
print '\nview file generated and available at ' + view_path + '\n'
def db_version():
# this is used to get the latest version in the database
current_version = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
print 'The current database version is ' + str(current_version)
def install_package(package_name):
if not package_name:
print "You need to specify a valid package name"
else:
current_platform = platform.system()
bin_base = ''
if current_platform == 'Windows':
bin_base = 'box\Scripts\pip'
else:
bin_base = 'box/bin/pip'
call([bin_base, 'install', package_name.lower()])
def run_tornado():
current_platform = platform.system()
bin_base = ''
if current_platform == 'Windows':
bin_base = 'box\Scripts\python'
else:
bin_base = 'box/bin/python'
call([bin_base,'ignite.py'])
def run_testrun():
current_platform = platform.system()
bin_base = ''
if current_platform == 'Windows':
bin_base = 'box\Scripts\python'
else:
bin_base = 'box/bin/python'
call([bin_base,'testrun.py'])
def run_gunicorn(arguments = None):
current_platform = platform.system()
if current_platform == 'Windows':
bin_base = 'box\Scripts\gunicorn'
else:
bin_base = 'box/bin/gunicorn'
option_list = [bin_base,'-b','0.0.0.0:'+str(SERVER_PORT),'greeny:app']
try:
restart_gunicorn()
if arguments:
for item in arguments:
option_list.append(item)
call(option_list)
else:
call([bin_base,'-b','0.0.0.0:'+str(SERVER_PORT),'-w','4','-k','tornado','greeny:app','--daemon'])
except:
if arguments:
for item in arguments:
option_list.append(item)
call(option_list)
else:
call([bin_base,'-b','0.0.0.0:'+str(SERVER_PORT),'-w','4','-k','tornado','greeny:app','--daemon'])
def restart_gunicorn():
proc = Popen(['ps','aux'], stdout=PIPE)
output=proc.communicate()[0].split('\n')
processes = output[2:]
ids = []
for item in processes:
if re.search('gunicorn',item):
values=[]
strings = item.split(" ")
for x in strings:
if x != "":
values.append(x)
ids.append(values[1])
ids.sort()
call(['kill','-9',ids[0]])
if len(sys.argv) > 1:
sysinput = sys.argv[1].lower()
if sysinput == '--help' or sysinput == '-h':
help()
elif sysinput == '--add' or sysinput == '-a':
if sys.argv[2]:
install_package(sys.argv[2])
else:
print "You need to specify a valid package name"
sys.exit()
elif sysinput == '--create' or sysinput == '-c':
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
db_create()
else:
print '\nPrevious database version found. Please use -m or --migrate option\n'
sys.exit()
elif sysinput == '--migrate' or sysinput == '-m':
db_migrate()
elif sysinput == '--initiate' or sysinput == '-i':
if len(sys.argv) > 2 and not sys.argv[2].isdigit():
add_controller(sys.argv[2])
else:
print 'Controller name can not be a number'
sys.exit()
elif sysinput == '--upgrade' or sysinput == '-u':
db_upgrade()
elif sysinput == '--version' or sysinput == '-v':
db_version()
elif sysinput == '--serve' or sysinput == '-s':
run_tornado()
elif sysinput == '--gserve' or sysinput == '-g':
if len(sys.argv) > 2:
run_gunicorn(sys.argv[2:])
else:
run_gunicorn()
elif sysinput == '--testrun' or sysinput == '-t':
run_testrun()
elif sysinput == '--downgrade' or sysinput == '-d':
if len(sys.argv) > 2 and sys.argv[2].isdigit():
db_downgrade(sys.argv[2])
else:
db_downgrade()
elif sysinput == '--new' or sysinput == '-n':
if len(sys.argv) > 2:
model_name = sys.argv[2].title()
raw_component = sys.argv[3:]
if raw_component:
model_components = []
for component in raw_component:
raw_field = component.split(':')
field_name = raw_field[0]
detail_components = raw_field[1].split('--')
if detail_components[0].lower() == 'string':
if len(detail_components) < 2:
detail_components.append('50')
insert_components = {
'field_name': field_name,
'field_property': detail_components
}
model_components.append(insert_components)
else:
print '\nNot enough parameters are provided. Model requires field definitions. See box.py -h for info\n'
sys.exit()
add_model(model_name, model_components)
else:
print '\nNot enough parameters are provided. See box.py -h for info\n'
else:
print '\nCommand not found. Please use --help for command options\n'
else:
print '\nNot enough parameters found. Please run box.py -h for complete explanations\n'
# end of file