forked from utero/manolo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db_importer.py
218 lines (179 loc) · 6.87 KB
/
db_importer.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
"""
Import data from django-manolo database into Manolo-v2
"""
import codecs
import dataset
import datetime
import json
import hashlib
import re
import sys
import os.path
import argparse
from unidecode import unidecode
import pyprind
def get_db_credentials(settings):
if settings == 'local':
from manolo.settings.local import DATABASES
return DATABASES['default']
if settings == 'production':
from manolo.settings.production import DATABASES
return DATABASES['default']
def get_tables_from_source_db(input_db):
db = dataset.connect("sqlite:///" + input_db)
return db.tables
class Importer(object):
def __init__(self, input_json, settings, limit, verbosity):
self.items = []
self.mytable = ''
self.verbosity = verbosity
self.limit = limit
self.input_json = input_json
self.settings = settings
self.ids_seen = self.get_ids_from_db()
def get_ids_from_db(self):
ids_seen = set()
credentials = get_db_credentials(self.settings)
if 'sqlite3' in credentials['ENGINE']:
db = dataset.connect("sqlite:///" + os.path.basename(credentials['NAME']))
if 'postgresql' in credentials['ENGINE']:
db = dataset.connect('postgresql://' +
credentials['USER'] + ':' +
credentials['PASSWORD'] + '@' +
credentials['HOST'] + ':' +
credentials['PORT'] + '/' +
credentials['NAME'])
res = db.query("select sha1 from visitors_visitor")
if res:
for i in res:
ids_seen.add(i['sha1'])
return ids_seen
def import_json(self):
with open(self.input_json) as handle:
for line in handle:
item = line.strip()
item = self.parse_item(json.loads(item))
if item['sha1'] in self.ids_seen:
if self.verbosity:
print("Duplicate item found: %s" % item['sha1'])
else:
self.ids_seen.add(item['sha1'])
self.items.append(item)
def parse_item(self, item):
if 'id' in item:
del item['id']
if 'num_visit' in item:
del item['num_visit']
if 'visitor' in item:
item['full_name'] = re.sub("\s+", " ", item['visitor']).strip()
del item['visitor']
if 'procedence' in item:
if item['procedence'] != '':
item['entity'] = item['procedence']
del item['procedence']
if 'entity' not in item:
item['entity'] = ''
if 'office' not in item:
item['office'] = ''
if 'host' in item:
item['host_name'] = re.sub("\s+", " ", item['host']).strip()
del item['host']
item['location'] = ''
if 'sede' in item:
if item['sede'] != '':
item['location'] = item['sede']
del item['sede']
if 'objective' in item:
item['reason'] = item['objective']
del item['objective']
if 'observation' in item:
del item['observation']
if 'meeting_place' not in item:
item['meeting_place'] = ''
if 'sha512' in item:
del item['sha512']
item['sha1'] = make_hash(
item['institution'],
item['full_name'],
item['id_document'],
item['id_number'],
item['date'],
item['time_start']
)
return item
def bulk_upload(self):
items_to_upload = []
append = items_to_upload.append
credentials = get_db_credentials(self.settings)
if 'sqlite3' in credentials['ENGINE']:
db = dataset.connect("sqlite:///" + os.path.basename(credentials['NAME']))
if 'postgresql' in credentials['ENGINE']:
db = dataset.connect('postgresql://' +
credentials['USER'] + ':' +
credentials['PASSWORD'] + '@' +
credentials['HOST'] + ':' +
credentials['PORT'] + '/' +
credentials['NAME'])
table = db['visitors_visitor']
print("Starting checks to see if we have this item in our database.")
if len(self.items) == 0:
print("Nothing to upload")
else:
for i in pyprind.prog_bar(range(len(self.items))):
item = self.items[i]
try:
item['date'] = datetime.datetime.strptime(
item['date'],
'%Y-%m-%d',
)
except ValueError:
item['date'] = None
append(item)
print("uploading %i records for table %s" % (len(items_to_upload), self.mytable))
table.insert_many(items_to_upload)
def make_hash(institution, full_name, id_document, id_number, date, time_start):
hash_input = str(
str(institution) +
str(unidecode(full_name)) +
str(unidecode(id_document)) +
str(unidecode(id_number)) +
str(date) +
str(time_start)
)
hash_output = hashlib.sha1()
hash_output.update(hash_input.encode('utf-8'))
return hash_output.hexdigest()
def import_from_json(input_json, settings, limit, verbosity):
importer = Importer(input_json, settings, limit, verbosity)
importer.import_json()
importer.bulk_upload()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Imports manolo_v1 database into v2')
parser.add_argument('-j', '--json', metavar='json',
required=False,
help='Import from JSONlines file')
parser.add_argument('-s', '--settings', metavar='settings',
required=True,
choices=['local', 'production'],
help='Data should be imported to local or production database?')
parser.add_argument('-l', '--limit', metavar='limit',
required=False,
help='Limits the number of items to import. Needs integer.')
parser.add_argument('-v', '--verbosity', metavar='verbosity',
required=False,
help='Prints to screen: 0 or 1')
args = parser.parse_args()
if args.verbosity is None:
verbosity = False
elif args.verbosity == '0':
verbosity = False
else:
verbosity = True
if args.limit is None:
limit = False
else:
limit = int(args.limit)
if args.json is None:
print("You need to enter either a Jsonlines file.")
sys.exit(1)
import_from_json(args.json, args.settings, limit, verbosity)