forked from limodou/uliweb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
4461 lines (3802 loc) · 157 KB
/
__init__.py
File metadata and controls
4461 lines (3802 loc) · 157 KB
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This module is used for wrapping SqlAlchemy to a simple ORM
# Author: limodou <limodou@gmail.com>
__all__ = ['Field', 'get_connection', 'Model', 'do_',
'set_debug_query', 'set_auto_create', 'set_auto_set_model',
'get_model', 'set_model', 'engine_manager',
'set_auto_transaction_in_web', 'set_auto_transaction_in_notweb',
'set_tablename_converter', 'set_check_max_length', 'set_post_do',
'rawsql', 'Lazy', 'set_echo', 'Session', 'get_session', 'set_session',
'CHAR', 'BLOB', 'TEXT', 'DECIMAL', 'Index', 'datetime', 'decimal',
'Begin', 'Commit', 'Rollback', 'Reset', 'ResetAll', 'CommitAll', 'RollbackAll',
'PICKLE', 'BIGINT', 'set_pk_type', 'PKTYPE', 'FILE', 'INT', 'SMALLINT', 'DATE',
'TIME', 'DATETIME', 'FLOAT', 'BOOLEAN', 'UUID', 'BINARY', 'VARBINARY',
'JSON', 'UUID_B',
'BlobProperty', 'BooleanProperty', 'DateProperty', 'DateTimeProperty',
'TimeProperty', 'DecimalProperty', 'FloatProperty', 'SQLStorage',
'IntegerProperty', 'Property', 'StringProperty', 'CharProperty',
'TextProperty', 'UnicodeProperty', 'Reference', 'ReferenceProperty',
'PickleProperty', 'BigIntegerProperty', 'FileProperty', 'JsonProperty',
'UUIDBinaryProperty', 'UUIDProperty',
'SelfReference', 'SelfReferenceProperty', 'OneToOne', 'ManyToMany',
'ReservedWordError', 'BadValueError', 'DuplicatePropertyError',
'ModelInstanceError', 'KindError', 'ConfigurationError', 'SaveError',
'BadPropertyTypeError', 'set_lazy_model_init',
'begin_sql_monitor', 'close_sql_monitor', 'set_model_config', 'text',
'get_object', 'get_cached_object',
'set_server_default', 'set_nullable', 'set_manytomany_index_reverse',
'NotFound', 'reflect_table',
'get_field_type', 'create_model', 'get_metadata', 'migrate_tables',
'print_model', 'get_model_property',
]
__auto_create__ = False
__auto_set_model__ = True
__auto_transaction_in_web__ = False
__auto_transaction_in_notweb__ = False
__debug_query__ = None
__default_engine__ = 'default'
__default_encoding__ = 'utf-8'
__zero_float__ = 0.0000005
__models__ = {}
__model_paths__ = {}
__pk_type__ = 'int'
__default_tablename_converter__ = None
__check_max_length__ = False #used to check max_length parameter
__default_post_do__ = None #used to process post_do topic
__nullable__ = False #not enabled null by default
__server_default__ = False #not enabled null by default
__manytomany_index_reverse__ = False
__lazy_model_init__ = False
import sys
import decimal
import threading
import datetime
import copy
import re
import cPickle as pickle
from uliweb.utils import date as _date
from uliweb.utils.common import (flat_list, classonlymethod, simple_value,
safe_str, import_attr)
from sqlalchemy import *
from sqlalchemy.sql import select, ColumnElement, text, true, and_, false
from sqlalchemy.pool import NullPool
import sqlalchemy.engine.base as EngineBase
from uliweb.core import dispatch
import threading
import warnings
import inspect
from uliweb.utils.sorteddict import SortedDict
from . import patch
Local = threading.local()
Local.dispatch_send = True
Local.conn = {}
Local.trans = {}
Local.echo = False
Local.echo_func = sys.stdout.write
class Error(Exception):pass
class NotFound(Error):
def __init__(self, message, model, key):
self.message = message
self.model = model
self.key = key
def __str__(self):
return "{0}({1}) instance can't be found".format(self.model.__name__, str(self.key))
class ModelNotFound(Error):pass
class ReservedWordError(Error):pass
class ModelInstanceError(Error):pass
class DuplicatePropertyError(Error):
"""Raised when a property is duplicated in a model definition."""
class BadValueError(Error):pass
class BadPropertyTypeError(Error):pass
class KindError(Error):pass
class ConfigurationError(Error):pass
class SaveError(Error):pass
_SELF_REFERENCE = object()
class Lazy(object): pass
class SQLStorage(dict):
"""
a dictionary that let you do d['a'] as well as d.a
"""
def __getattr__(self, key): return self[key]
def __setattr__(self, key, value):
if self.has_key(key):
raise SyntaxError('Object exists and cannot be redefined')
self[key] = value
def __repr__(self): return '<SQLStorage ' + dict.__repr__(self) + '>'
def set_auto_create(flag):
global __auto_create__
__auto_create__ = flag
def set_auto_transaction_in_notweb(flag):
global __auto_transaction_in_notweb__
__auto_transaction_in_notweb__ = flag
def set_auto_transaction_in_web(flag):
global __auto_transaction_in_web__
__auto_transaction_in_web__ = flag
def set_auto_set_model(flag):
global __auto_set_model__
__auto_set_model__ = flag
def set_debug_query(flag):
global __debug_query__
__debug_query__ = flag
def set_check_max_length(flag):
global __check_max_length__
__check_max_length__ = flag
def set_post_do(func):
global __default_post_do__
__default_post_do__ = func
def set_nullable(flag):
global __nullable__
__nullable__ = flag
def set_server_default(flag):
global __server_default__
__server_default__ = flag
def set_manytomany_index_reverse(flag):
global __manytomany_index_reverse__
__manytomany_index_reverse__ = flag
def set_encoding(encoding):
global __default_encoding__
__default_encoding__ = encoding
def set_dispatch_send(flag):
global Local
Local.dispatch_send = flag
def set_tablename_converter(converter=None):
global __default_tablename_converter__
__default_tablename_converter__ = converter
def set_lazy_model_init(flag):
global __lazy_model_init__
__lazy_model_init__ = flag
def get_tablename(tablename):
global __default_tablename_converter__
c = __default_tablename_converter__
if not c:
c = lambda x:x.lower()
return c(tablename)
def get_dispatch_send(default=True):
global Local
if not hasattr(Local, 'dispatch_send'):
Local.dispatch_send = default
return Local.dispatch_send
def set_echo(flag, time=None, explain=False, caller=True, session=None):
global Local
Local.echo = flag
Local.echo_args = {'time':time, 'explain':explain, 'caller':caller,
'session':None}
def set_pk_type(name):
global __pk_type__
__pk_type__ = name
def PKTYPE():
if __pk_type__ == 'int':
return int
else:
return BIGINT
def PKCLASS():
if __pk_type__ == 'int':
return Integer
else:
return BigInteger
class NamedEngine(object):
def __init__(self, name, options):
self.name = name
d = SQLStorage({
'engine_name':name,
'connection_args':{},
'debug_log':None,
'connection_type':'long',
'duplication':False,
})
strategy = options.pop('strategy', None)
d.update(options)
if d.get('debug_log', None) is None:
d['debug_log'] = __debug_query__
if d.get('connection_type') == 'short':
d['connection_args']['poolclass'] = NullPool
if strategy:
d['connection_args']['strategy'] = strategy
self.options = d
self.engine_instance = None
self.metadata = MetaData()
self._models = {}
self.local = threading.local() #used to save thread vars
self._create()
def _get_models(self):
if self.options.duplication:
return engine_manager[self.options.duplication].models
else:
return self._models
models = property(fget=_get_models)
def _create(self, new=False):
c = self.options
db = self.engine_instance
if not self.engine_instance or new:
args = c.get('connection_args', {})
self.engine_instance = create_engine(c.get('connection_string'), **args)
self.engine_instance.echo = c['debug_log']
self.engine_instance.metadata = self.metadata
self.metadata.bind = self.engine_instance
return self.engine_instance
def session(self, create=True):
"""
Used to created default session
"""
if hasattr(self.local, 'session'):
return self.local.session
else:
if create:
s = Session(self.name)
self.local.session = s
return s
def set_session(self, session):
self.local.session = session
@property
def engine(self):
return self.engine_instance
def print_pool_status(self):
if self.engine.pool:
print self.engine.pool.status()
class EngineManager(object):
def __init__(self):
self.engines = {}
def add(self, name, connection_args):
self.engines[name] = engine = NamedEngine(name, connection_args)
return engine
def get(self, name=None):
name = name or __default_engine__
engine = self.engines.get(name)
if not engine:
raise Error('Engine %s is not exists yet' % name)
return engine
def __getitem__(self, name=None):
return self.get(name)
def __setitem__(self, name, connection_args):
return self.add(name, connection_args)
def __contains__(self, name):
return name in self.engines
def items(self):
return self.engines.items()
engine_manager = EngineManager()
class Session(object):
"""
used to manage relationship between engine_name and connect
can also manage transcation
"""
def __init__(self, engine_name=None, auto_transaction=None,
auto_close=True, post_commit=None, post_commit_once=None):
"""
If auto_transaction is True, it'll automatically start transacation
in web environment, it'll be commit or rollback after the request finished
and in no-web environment, you should invoke commit or rollback yourself.
"""
self.engine_name = engine_name or __default_engine__
self.auto_transaction = auto_transaction
self.auto_close = auto_close
self.engine = engine_manager[engine_name]
self._conn = None
self._trans = None
self.local_cache = {}
self.post_commit = post_commit or []
self.post_commit_once = post_commit_once or []
def __str__(self):
return '<Session engine_name:%s, auto_transaction=%r, auto_close=%r>' % (
self.engine_name, self.auto_transaction, self.auto_close)
@property
def need_transaction(self):
from uliweb import is_in_web
global __auto_transaction_in_notweb__, __auto_transaction_in_web__
if self.auto_transaction is not None:
return self.auto_transaction
else:
#distinguish in web or not web environment
if is_in_web():
return __auto_transaction_in_web__
else:
return __auto_transaction_in_notweb__
@property
def connection(self):
if self._conn:
return self._conn
else:
self._conn = self.engine.engine.connect()
return self._conn
def execute(self, query, *args):
t = self.need_transaction
try:
if t:
self.begin()
return self.connection.execute(query, *args)
except:
if t:
self.rollback()
raise
def set_echo(self, flag, time=None, explain=False, caller=True):
global set_echo
set_echo(flag, time, explain, caller, self)
def do_(self, query, args=None):
global do_
return do_(query, self, args)
def begin(self):
if not self._trans:
self.connection
self._trans = self._conn.begin()
return self._trans
def commit(self):
if self._trans and self._conn.in_transaction():
self._trans.commit()
self._trans = None
if self.auto_close:
self._close()
#add post commit hook
if self.post_commit:
if not isinstance(self.post_commit, (list, tuple)):
self.post_commit = [self.post_commit]
for c in self.post_commit:
c()
#add post commit once hook
if self.post_commit_once:
if not isinstance(self.post_commit_once, (list, tuple)):
post_commit_once = [self.post_commit_once]
else:
post_commit_once = self.post_commit_once
self.post_commit_once = []
for c in post_commit_once:
c()
def in_transaction(self):
if not self._conn:
return False
return self._conn.in_transaction()
def rollback(self):
if self._trans and self._conn.in_transaction():
self._trans.rollback()
self._trans = None
if self.auto_close:
self._close()
def _close(self):
if self._conn:
self._conn.close()
self._conn = None
self.local_cache = {}
if self.engine.options.connection_type == 'short':
self.engine.engine.dispose()
def close(self):
self.rollback()
self._close()
def get_local_cache(self, key, creator=None):
value = self.local_cache.get(key)
if value:
return value
if callable(creator):
value = creator()
else:
value = creator
if value:
self.local_cache[key] = value
return value
def get_connection(connection='', engine_name=None, connection_type='long', **args):
"""
Creating an NamedEngine or just return existed engine instance
if '://' include in connection parameter, it'll create new engine object
otherwise return existed engine isntance
"""
engine_name = engine_name or __default_engine__
if '://' in connection:
d = {
'connection_string':connection,
'connection_args':args,
'connection_type':connection_type,
}
return engine_manager.add(engine_name, d).engine
else:
connection = connection or __default_engine__
if connection in engine_manager:
return engine_manager[connection].engine
else:
raise Error("Can't find engine %s" % connection)
def get_metadata(engine_name=None):
"""
get metadata according used for alembic
It'll import all tables
"""
dispatch.get(None, 'load_models')
engine = engine_manager[engine_name]
for tablename, m in engine.models.items():
get_model(tablename, engine_name, signal=False)
if hasattr(m, '__dynamic__') and getattr(m, '__dynamic__'):
m.table.__mapping_only__ = True
return engine.metadata
def get_session(ec=None, create=True):
"""
ec - engine_name or connection
"""
ec = ec or __default_engine__
if isinstance(ec, (str, unicode)):
session = engine_manager[ec].session(create=True)
elif isinstance(ec, Session):
session = ec
else:
raise Error("Connection %r should be existed engine name or Session object" % ec)
return session
def set_session(session=None, engine_name='default'):
if not session:
session = Session()
engine_manager[engine_name].set_session(session)
return session
def Reset(ec=None):
session = get_session(ec, False)
if session:
session.close()
def ResetAll():
for k, v in engine_manager.items():
session = v.session(create=False)
if session:
session.close()
@dispatch.bind('post_do', kind=dispatch.LOW)
def default_post_do(sender, query, conn, usetime):
if __default_post_do__:
__default_post_do__(sender, query, conn, usetime)
re_placeholder = re.compile(r'%\(\w+\)s')
def rawsql(query, ec=None):
"""
ec could be engine name or engine instance
"""
if isinstance(query, Result):
query = query.get_query()
ec = ec or __default_engine__
if isinstance(ec, (str, unicode)):
engine = engine_manager[ec]
dialect = engine.engine.dialect
else:
dialect = ec.dialect
if isinstance(query, (str, unicode)):
return query
#return str(query.compile(compile_kwargs={"literal_binds": True})).replace('\n', '') + ';'
comp = query.compile(dialect=dialect)
b = re_placeholder.search(comp.string)
if b:
return comp.string % comp.params
else:
if dialect.name == 'postgresql':
return comp.string
else:
params = []
for k in comp.positiontup:
v = comp.params[k]
params.append(repr(simple_value(v)))
line = comp.string.replace('?', '%s') % tuple(params)
return line.replace('\n', '')
def get_engine_name(ec=None):
"""
Get the name of a engine or session
"""
ec = ec or __default_engine__
if isinstance(ec, (str, unicode)):
return ec
elif isinstance(ec, Session):
return ec.engine_name
else:
raise Error("Parameter ec should be an engine_name or Session object, but %r found" % ec)
def print_model(model, engine_name=None, skipblank=False):
from sqlalchemy.schema import CreateTable, CreateIndex
engine = engine_manager[engine_name].engine
M = get_model(model)
t = M.table
s = []
s.append("%s;" % str(CreateTable(t).compile(dialect=engine.dialect)).rstrip())
for x in t.indexes:
s.append("%s;" % CreateIndex(x))
sql = '\n'.join(s)
if skipblank:
return re.sub('[\t\n]+', '', sql)
else:
return sql
def do_(query, ec=None, args=None):
"""
Execute a query
"""
from time import time
from uliweb.utils.common import get_caller
conn = get_session(ec)
b = time()
result = conn.execute(query, *(args or ()))
t = time() - b
dispatch.call(ec, 'post_do', query, conn, t)
flag = False
sql = ''
if hasattr(Local, 'echo') and Local.echo:
if hasattr(Local, 'echo_args'):
_ec = Local.echo_args.get('session')
else:
_ec = None
engine_name = get_engine_name(ec)
_e = get_engine_name(_ec)
if not _ec or _ec and _ec == _e:
if hasattr(Local, 'echo_args') and Local.echo_args['time']:
if t >= Local.echo_args['time']:
sql = rawsql(query)
flag = True
else:
sql = rawsql(query)
flag = True
if flag:
print '\n===>>>>> [%s]' % engine_name,
if hasattr(Local, 'echo_args') and Local.echo_args['caller']:
v = get_caller(skip=__file__)
print '(%s:%d:%s)' % v
else:
print
print sql+';'
if hasattr(Local, 'echo_args') and Local.echo_args['explain'] and sql:
r = conn.execute('explain '+sql).fetchone()
print '\n----\nExplain: %s' % ''.join(["%s=%r, " % (k, v) for k, v in r.items()])
print '===<<<<< time used %fs\n' % t
return result
def save_file(result, filename, encoding='utf8', headers=None,
convertors=None, visitor=None, **kwargs):
"""
save query result to a csv file
visitor can used to convert values, all value should be convert to string
visitor function should be defined as:
def visitor(keys, values, encoding):
#return new values []
convertors is used to convert single column value, for example:
convertors = {'field1':convert_func1, 'fields2':convert_func2}
def convert_func1(value, data):
value is value of field1
data is the record
if visitor and convertors all provided, only visitor is available.
headers used to convert column to a provided value
"""
import csv
from uliweb.utils.common import simple_value
convertors = convertors or {}
headers = headers or {}
def convert(k, v, data):
f = convertors.get(k)
if f:
v = f(v, data)
return v
def convert_header(k):
return headers.get(k, k)
def _r(x):
if isinstance(x, (str, unicode)):
return re.sub('\r\n|\r|\n', ' ', x)
else:
return x
if isinstance(filename, (str, unicode)):
f = open(filename, 'wb')
need_close = True
else:
f = filename
need_close = False
try:
w = csv.writer(f, **kwargs)
w.writerow([simple_value(convert_header(x), encoding=encoding) for x in result.keys()])
for row in result:
if visitor and callable(visitor):
_row = visitor(result.keys, row.values(), encoding)
else:
_row = [convert(k, v, row) for k, v in zip(result.keys(), row.values())]
r = [simple_value(_r(x), encoding=encoding) for x in _row]
w.writerow(r)
finally:
if need_close:
f.close()
def Begin(ec=None):
session = get_session(ec)
return session.begin()
def Commit(ec=None, close=None):
if close:
warnings.simplefilter('default')
warnings.warn("close parameter will not need at all.", DeprecationWarning)
session = get_session(ec, False)
if session:
return session.commit()
def CommitAll(close=None):
"""
Commit all transactions according Local.conn
"""
if close:
warnings.simplefilter('default')
warnings.warn("close parameter will not need at all.", DeprecationWarning)
for k, v in engine_manager.items():
session = v.session(create=False)
if session:
session.commit()
def Rollback(ec=None, close=None):
if close:
warnings.simplefilter('default')
warnings.warn("close parameter will not need at all.", DeprecationWarning)
session = get_session(ec, False)
if session:
return session.rollback()
def RollbackAll(close=None):
"""
Rollback all transactions, according Local.conn
"""
if close:
warnings.simplefilter('default')
warnings.warn("close parameter will not need at all.", DeprecationWarning)
for k, v in engine_manager.items():
session = v.session(create=False)
if session:
session.rollback()
def check_reserved_word(f):
if f in ['put', 'save', 'table', 'tablename', 'c', 'columns', 'manytomany'] or f in dir(Model):
raise ReservedWordError(
"Cannot define property using reserved word '%s'. " % f
)
def set_model(model, tablename=None, created=None, appname=None, model_path=None):
"""
Register an model and tablename to a global variable.
model could be a string format, i.e., 'uliweb.contrib.auth.models.User'
:param appname: if no appname, then archive according to model
item structure
created
model
model_path
appname
For dynamic model you should pass model_path with '' value
"""
if isinstance(model, type) and issubclass(model, Model):
#use alias first
tablename = model._alias or model.tablename
tablename = tablename.lower()
#set global __models__
d = __models__.setdefault(tablename, {})
engines = d.get('config', {}).pop('engines', ['default'])
if isinstance(engines, (str, unicode)):
engines = [engines]
d['engines'] = engines
item = {}
if created is not None:
item['created'] = created
else:
item['created'] = None
if isinstance(model, (str, unicode)):
if model_path is None:
model_path = model
else:
model_path = model_path
if not appname:
appname = model.rsplit('.', 2)[0]
#for example 'uliweb.contrib.auth.models.User'
model = None
else:
appname = model.__module__.rsplit('.', 1)[0]
if model_path is None:
model_path = model.__module__ + '.' + model.__name__
else:
model_path = ''
#for example 'uliweb.contrib.auth.models'
model.__engines__ = engines
item['model'] = model
item['model_path'] = model_path
item['appname'] = appname
d['model_path'] = model_path
d['appname'] = appname
for name in engines:
if not isinstance(name, (str, unicode)):
raise BadValueError('Engine name should be string type, but %r found' % name)
engine_manager[name].models[tablename] = item.copy()
def set_model_config(model_name, config, replace=False):
"""
This function should be only used in initialization phrase
:param model_name: model name it's should be string
:param config: config should be dict. e.g.
{'__mapping_only__', '__tablename__', '__ext_model__'}
:param replace: if True, then replace original config, False will update
"""
assert isinstance(model_name, str)
assert isinstance(config, dict)
d = __models__.setdefault(model_name, {})
if replace:
d['config'] = config
else:
c = d.setdefault('config', {})
c.update(config)
def create_model(modelname, fields, indexes=None, basemodel=None, **props):
"""
Create model dynamically
:param fields: Just format like [
{'name':name, 'type':type, ...},
...
]
type should be a string, eg. 'str', 'int', etc
kwargs will be passed to Property.__init__() according field type,
it'll be a dict
:param props: Model attributes, such as '__mapping_only__', '__replace__'
:param indexes: Multiple fields index, single index can be set directly using `index=True`
to a field, the value format should be:
[
{'name':name, 'fields':[...], ...},
]
e.g. [
{'name':'audit_idx', 'fields':['table_id', 'obj_id']}
]
for kwargs can be ommited.
:param basemodel: Will be the new Model base class, so new Model can inherited
parent methods, it can be a string or a real class object
"""
assert not props or isinstance(props, dict)
assert not indexes or isinstance(indexes, list)
props = SortedDict(props or {})
props['__dynamic__'] = True
props['__config__'] = False
for p in fields:
kwargs = p.copy()
name = kwargs.pop('name')
_type = kwargs.pop('type')
#if the key is start with '_', then remove it
for k in kwargs.keys():
if k.startswith('_'):
kwargs.pop(k, None)
field_type = get_field_type(_type)
prop = field_type(**kwargs)
props[name] = prop
if basemodel:
model = import_attr(basemodel)
# model.clear_relation()
else:
model = Model
# try:
# old = get_model(modelname, signal=False)
# old.clear_relation()
# except ModelNotFound as e:
# pass
cls = type(str(modelname.title()), (model,), props)
tablename = props.get('__tablename__', modelname)
set_model(cls, tablename, appname=__name__, model_path='')
get_model(modelname, signal=False, reload=True)
indexes = indexes or []
for x in indexes:
kwargs = x.copy()
name = kwargs.pop('name')
fields = kwargs.pop('fields')
#if the key is start with '_', then remove it
for k in kwargs.keys():
if k.startswith('_'):
kwargs.pop(k, None)
if not isinstance(fields, (list, tuple)):
raise ValueError("Index value format is not right, the value is %r" % indexes)
props = []
for y in fields:
props.append(cls.c[y])
Index(name, *props, **kwargs)
return cls
def valid_model(model, engine_name=None):
if isinstance(model, type) and issubclass(model, Model):
return True
if engine_name:
engine = engine_manager[engine_name]
return model in engine.models
else:
return True
def check_model_class(model_cls):
# """
# :param model: Model instance
# Model.__engines__ could be a list, so if there are multiple then use
# the first one
# """
#check dynamic flag
if getattr(model_cls, "__dynamic__", False):
return True
#check the model_path
model_path = model_cls.__module__ + '.' + model_cls.__name__
_path = __models__.get(model_cls.tablename, {}).get('model_path', '')
if _path and model_path != _path:
return False
return True
def find_metadata(model):
"""
:param model: Model instance
"""
engine_name = model.get_engine_name()
engine = engine_manager[engine_name]
return engine.metadata
def get_model(model, engine_name=None, signal=True, reload=False):
"""
Return a real model object, so if the model is already a Model class, then
return it directly. If not then import it.
if engine_name is None, then if there is multi engines defined, it'll use
'default', but if there is only one engine defined, it'll use this one
:param dispatch: Used to switch dispatch signal
"""
if isinstance(model, type) and issubclass(model, Model):
return model
if not isinstance(model, (str, unicode)):
raise Error("Model %r should be string or unicode type" % model)
#make model name is lower case
model = model.lower()
model_item = __models__.get(model)
if not model_item:
model_item = dispatch.get(None, 'find_model', model_name=model)
if model_item:
if not engine_name:
#search according model_item, and it should has only one engine defined
engines = model_item['engines']
if len(engines) > 1:
engine_name = __default_engine__
else:
engine_name = engines[0]
engine = engine_manager[engine_name]
item = engine._models.get(model)
#process duplication
if not item and engine.options.duplication:
_item = engine.models.get(model)
if _item:
item = _item.copy()
item['model'] = None
engine._models[model] = item
if item:
loaded = False #True, model is already loaded, so consider if it needs be cached
m = item['model']
m_config = __models__[model].get('config', {})
if isinstance(m, type) and issubclass(m, Model):
loaded = True
if reload:
loaded = False
#add get_model previous hook
if signal:
model_inst = dispatch.get(None, 'get_model', model_name=model, model_inst=m,
model_info=item, model_config=m_config) or m
if m is not model_inst: