usr bin env python coding utf-8 from __future__ import division unicod

  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
#!/usr/bin/env python
# coding: utf-8
from __future__ import division, unicode_literals
import yaml
import decimal
import sys
from sqlalchemy.orm import sessionmaker
from AccessDataBase import BaseEngine
from sqlalchemy import create_engine
from sqlalchemy.orm.collections import InstrumentedList
engine = create_engine(BaseEngine.engine, convert_unicode=True)
Session = sessionmaker(engine)
session = Session()
def get_model(name):
obj = getattr(BaseEngine, name)
if type(BaseEngine.Base) == type(obj) and (not (obj is BaseEngine.Base)):
res = session.query(obj).all()
if len(res) > 0:
return obj
def get_model_list():
res = []
for key in BaseEngine.__dict__.keys():
tmp = get_model(key)
if tmp:
res.append(tmp)
return res
def dump_yaml(model):
""" Обджекты одного типа """
to_dump = []
res = session.query(model).all()
name = model.__tablename__
for instance in res:
data = instance.__dict__.copy()
del data['_sa_instance_state']
for k, v in data.items():
if isinstance(data[k], decimal.Decimal):
data[k] = float(v)
fk_list = getattr(instance, k[:-3], None)
if fk_list and isinstance(fk_list, InstrumentedList):
data[k[:-3] + '_fk'] = {'name': k,
'ids': [x.id for x in fk_list]}
to_dump.append(data)
with open("Fixtures/" + name + ".yml", "w") as outfile:
outfile.write(yaml.safe_dump(to_dump,
default_flow_style=False,
allow_unicode=True
))
print name + " dumped"
def load_yaml(model):
name = model.__tablename__
name = "Fixtures/" + name + ".yml"
try:
for data in yaml.load(open(name, "r")):
if data.get('id'):
res = session.query(model).get(data['id'])
del data['id']
if res:
for k, v in data.items():
#print isinstance(v, list)
if k[-3:] == '_fk' :
import ipdb; ipdb.set_trace()
setattr(res, k, v)
session.add(res)
session.commit()
continue
# я забыл что я делаю тут ниже
_id = {}
for k, v in data.items():
if k[-3:] == '_id' or k == 'active': # donot dave pk
_id[k] = data[k]
del data[k]
m = model(**data)
for k, v in _id.items():
setattr(m, k, v)
session.add(m)
session.commit()
print 'Loaded:', name
except IOError:
print 'No such file', name
if len(sys.argv) < 2:
print 'try -list'
sys.exit()
action, args = sys.argv[1], sys.argv[2:]
if action == '-list':
print "You can dump in files this models:"
print [x.__tablename__ for x in get_model_list()]
elif action == '-dump':
if len(args) > 1:
for model_name in args:
dump_yaml(get_model(model_name))
else:
print '-' * 5 + 'Start' + '-' * 5
[dump_yaml(x) for x in get_model_list()]
print '-' * 5 + 'Finish' + '-' * 5
elif action == '-load':
if len(args) > 1:
for model_name in args:
dump_yaml(get_model(model_name))
else:
print '-' * 5 + 'Start' + '-' * 5
for key in BaseEngine.__dict__.keys():
obj = getattr(BaseEngine, key)
if type(BaseEngine.Base) == type(obj) and (not (obj is BaseEngine.Base)):
load_yaml(obj)
print '-' * 5 + 'Finish' + '-' * 5
else:
print """-list for show all tables
-dump for save data in yaml files
-load for load from yaml files"""