Repository navigation
Expand file tree
/
Copy path__init__.py
More file actions
3465 lines (2943 loc) · 122 KB
/
Copy path__init__.py
File metadata and controls
3465 lines (2943 loc) · 122 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',
'CHAR', 'BLOB', 'TEXT', 'DECIMAL', 'Index', 'datetime', 'decimal',
'Begin', 'Commit', 'Rollback', 'Reset', 'ResetAll', 'CommitAll', 'RollbackAll',
'PICKLE', 'BIGINT', 'set_pk_type', 'PKTYPE',
'BlobProperty', 'BooleanProperty', 'DateProperty', 'DateTimeProperty',
'TimeProperty', 'DecimalProperty', 'FloatProperty', 'SQLStorage',
'IntegerProperty', 'Property', 'StringProperty', 'CharProperty',
'TextProperty', 'UnicodeProperty', 'Reference', 'ReferenceProperty',
'PickleProperty', 'BigIntegerProperty',
'SelfReference', 'SelfReferenceProperty', 'OneToOne', 'ManyToMany',
'ReservedWordError', 'BadValueError', 'DuplicatePropertyError',
'ModelInstanceError', 'KindError', 'ConfigurationError', 'SaveError',
'BadPropertyTypeError', 'FILE', 'Begin', 'Commit', 'Rollback',
'CommitAll', 'RollbackAll', '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',
]
__auto_create__ = False
__auto_set_model__ = True
__auto_transaction_in_web__ = False
__auto_transaction_in_notweb__ = False
__debug_query__ = None
__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)
from sqlalchemy import *
from sqlalchemy.sql import select, ColumnElement, text, true
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, id):
self.message = message
self.model = model
self.id = id
def __str__(self):
return "%s(%s) instance can't be found" % (self.model.__name__, str(self.id))
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',
})
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 _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
@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 = 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='default', auto_transaction=None,
auto_close=True):
"""
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
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 = {}
@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()
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='default', 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
"""
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'
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
"""
engine = engine_manager[engine_name]
for tablename, m in engine.models.items():
if not m['model']:
get_model(tablename, engine_name)
return engine.metadata
def get_session(ec=None, create=True):
"""
ec - engine_name or connection
"""
ec = ec or 'default'
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 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):
if isinstance(query, Result):
query = query.get_query()
ec = ec or 'default'
engine = engine_manager[ec]
dialect = engine.engine.dialect
comp = query.compile(dialect=dialect)
b = re_placeholder.search(comp.string)
if b:
return comp.string % comp.params
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'
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 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):
"""
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
with open(filename, 'wb') as f:
w = csv.writer(f)
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)
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'] or f in dir(Model):
raise ReservedWordError(
"Cannot define property using reserved word '%s'. " % f
)
def set_model(model, tablename=None, created=None):
"""
Register an model and tablename to a global variable.
model could be a string format, i.e., 'uliweb.contrib.auth.models.User'
item structure
created
model
model_path
appname
"""
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)):
model_path = model
appname = model.rsplit('.', 2)[0]
#for example 'uliweb.contrib.auth.models.User'
model = None
else:
appname = model.__module__.rsplit('.', 1)[0]
model_path = model.__module__ + '.' + model.__name__
#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):
"""
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__':xxx}
"""
assert isinstance(model_name, str)
assert isinstance(config, dict)
d = __models__.setdefault(model_name, {})
d['config'] = config
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
# """
# tablename = model._alias or model.tablename
# name = model.__name__
# appname = model.__module__
# model_path = appname + '.' + name
# return (tablename not in __models__)
#
#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):
"""
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
"""
if model is _SELF_REFERENCE:
return model
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 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'
else:
engine_name = engines[0]
engine = engine_manager[engine_name]
item = engine.models.get(model)
if item:
m = item['model']
if isinstance(m, type) and issubclass(m, Model):
return m
else:
mod_path, name = item['model_path'].rsplit('.', 1)
mod = __import__(mod_path, fromlist=['*'])
model_inst = getattr(mod, name)
if model_inst._bound_classname == model:
model_inst = model_inst._use(engine_name)
item['model'] = model_inst
else:
config = __models__[model].get('config', {})
if config:
for k, v in config.items():
setattr(model_inst, k, v)
item['model'] = model_inst
model_inst._alias = model
model_inst._engine_name = engine_name
for k, v in model_inst.properties.items():
v.__property_config__(model_inst, k)
#add bind process
model_inst.bind(engine.metadata)
return model_inst
raise Error("Can't found the model %s in engine %s" % (model, engine_name))
def get_object_id(engine_name, tablename, id):
return 'OC:%s:%s:%s' % (engine_name, tablename, str(id))
def get_object(table, id, condition=None, cache=False, fields=None, use_local=False, session=None):
"""
Get obj in Local.object_caches first and also use get(cache=True) function if
not found in object_caches
"""
from uliweb import functions, settings
model = get_model(table)
#if id is an object of Model, so get the real id value
if isinstance(id, Model):
return id
if cache:
if use_local:
s = get_session(session)
key = get_object_id(s.engine_name, model.tablename, id)
value = s.get_local_cache(key)
if value:
return value
obj = model.get(id, condition=condition, fields=fields, cache=True)
if use_local:
value = s.get_local_cache(key, obj)
else:
obj = model.get(id, condition=condition, fields=fields)
return obj
def get_cached_object(table, id, condition=None, cache=True, fields=None, use_local=True, session=None):
return get_object(table, id, condition, cache, fields, use_local, session)
class SQLMointor(object):
def __init__(self, key_length=65, record_details=False):
self.count = SortedDict()
self.total = 0
self.key_length = key_length
self.details = []
self.record_details = record_details
def post_do(sender, query, conn, usetime, self=self):
sql = str(query)
c = self.count.setdefault(sql, {'count':0, 'time':0})
c['count'] += 1
c['time'] += usetime
self.total += 1
if self.record_details:
self.details.append(rawsql(query))
self.post_do = post_do
def print_(self, message=''):
print
print '====== sql execution count %d <%s> =======' % (self.total, message)
for k, v in sorted(self.count.items(), key=lambda x:x[1]):
k = k.replace('\r', '')
k = k.replace('\n', '')
if self.key_length and self.key_length>1 and len(k) > self.key_length:
k = k[:self.key_length-3]+'...'
if self.key_length > 0:
format = "%%-%ds %%3d %%.3f" % self.key_length
else:
format = "%s %3d %.3f"
print format % (k, v['count'], v['time'])
if self.record_details:
print '====== sql statements %d ====' % self.total
for line in self.details:
print '.', line
print
def close(self):
self.count = {}
self.total = 0
self.details = []
def begin_sql_monitor(key_length=70, record_details=False):
sql_monitor = SQLMointor(key_length, record_details)
dispatch.bind('post_do')(sql_monitor.post_do)
return sql_monitor
def close_sql_monitor(monitor):
dispatch.unbind('post_do', monitor.post_do)
monitor.close()
class ModelMetaclass(type):
def __init__(cls, name, bases, dct):
super(ModelMetaclass, cls).__init__(name, bases, dct)
if name == 'Model':
return
cls._set_tablename()
#check if cls is matched with __models__ module_path
if not check_model_class(cls):
return
cls.properties = {}
cls._fields_list = []
defined = set()
for base in bases:
if hasattr(base, 'properties'):
cls.properties.update(base.properties)
cls._manytomany = {}
for attr_name in dct.keys():
attr = dct[attr_name]
if isinstance(attr, Property):
cls.add_property(attr_name, attr, set_property=False, config=not __lazy_model_init__)
if isinstance(attr, ManyToMany):
cls._manytomany[attr_name] = attr
#if there is already defined primary_key, the id will not be primary_key
#enable multi primary
#has_primary_key = bool([v for v in cls.properties.itervalues() if 'primary_key' in v.kwargs])
#add __without_id__ attribute to model, if set it, uliorm will not
#create 'id' field for the model
#if there is already has primary key, then id will not created
#change in 0.2.6 version
without_id = getattr(cls, '__without_id__', False)
if 'id' not in cls.properties and not without_id:
cls.properties['id'] = f = Field(PKTYPE(), autoincrement=True,
primary_key=True, default=None, nullable=False, server_default=None)
if not __lazy_model_init__:
f.__property_config__(cls, 'id')
setattr(cls, 'id', f)
fields_list = [(k, v) for k, v in cls.properties.items()]
fields_list.sort(lambda x, y: cmp(x[1].creation_counter, y[1].creation_counter))
cls._fields_list = fields_list
if cls._bind and not __lazy_model_init__:
cls.bind(auto_create=__auto_create__)
class LazyValue(object):
def __init__(self, name, property):
self.name = name
self.property = property
def __get__(self, model_instance, model_class):
if model_instance is None:
return self
return self.property.get_lazy(model_instance, self.name, self.property.default)
def __set__(self, model_instance, value):
if model_instance is None:
return
setattr(model_instance, self.name, value)
class Property(object):
data_type = str
field_class = String
creation_counter = 0
property_type = 'column' #Property type: 'column', 'compound', 'relation'
server_default = None
def __init__(self, verbose_name=None, name=None, default=None,
required=False, validators=None, choices=None, max_length=None,
hint='', auto=None, auto_add=None, type_class=None, type_attrs=None,
placeholder='', extra=None,
sequence=False, **kwargs):
self.verbose_name = verbose_name
self.property_name = None
self.name = name
self.default = default
self.required = required
self.auto = auto
self.auto_add = auto_add
self.validators = validators or []
self.hint = hint
if not isinstance(self.validators, (tuple, list)):
self.validators = [self.validators]
self.choices = choices
self.max_length = max_length
self.kwargs = kwargs
self.sequence = sequence
self.creation_counter = Property.creation_counter
self.value = None
self.placeholder = placeholder
self.extra = extra or {}
self.type_attrs = type_attrs or {}
self.type_class = type_class or self.field_class