-
Notifications
You must be signed in to change notification settings - Fork 0
/
import.py
185 lines (155 loc) · 5.85 KB
/
import.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
import sys, getopt
import json
from datetime import datetime
from pymodm.connection import connect
from pymongo.write_concern import WriteConcern
from pymodm import EmbeddedMongoModel, MongoModel, fields
class Product(EmbeddedMongoModel):
name = fields.CharField()
description = fields.CharField(blank=True)
categories = fields.ListField(blank=True)
quantity = fields.IntegerField(blank=True)
createdAt = fields.DateTimeField()
updatedAt = fields.DateTimeField(blank=True)
class Meta:
write_concern = WriteConcern(j=True)
connection_alias = 'kuro'
collection_name = 'products'
class Shop(MongoModel):
name = fields.CharField(blank=True)
location = fields.PointField(blank=True)
products = fields.EmbeddedDocumentListField(Product, blank=True)
address = fields.ReferenceField('Address', blank=True)
createdAt = fields.DateTimeField()
updatedAt = fields.DateTimeField(blank=True)
class Meta:
write_concern = WriteConcern(j=True)
connection_alias = 'kuro'
collection_name = 'shops'
class Address(MongoModel):
shop = fields.ReferenceField(Shop, blank=True)
address = fields.CharField()
city = fields.CharField(blank=True)
postCode = fields.IntegerField(blank=True)
class Meta:
write_concern = WriteConcern(j=True)
connection_alias = 'kuro'
collection_name = 'addresses'
def main(argv):
user = ''
password = ''
try:
opts, args = getopt.getopt(argv,"hu:p:",["user=","password="])
except getopt.GetoptError:
print("import.py -u <user> -p <password>")
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print("import.py -u <user> -p <password>")
sys.exit()
elif opt in ("-u", "--user"):
user = arg
elif opt in ("-p", "--password"):
password = arg
if(user == '' or password == ''):
print("username or password not provided")
sys.exit()
# Connect to MongoDB and call the connection "kuro".
connect("mongodb://"+user+":"+password+"@37.120.164.78:27017/kuro", alias="kuro")
post_codes = []
cities = []
insertProducts = []
start = datetime.now()
print('Started: ', start)
# Create all products
with open('./products.json', 'r') as f:
products = json.load(f)
## Remove all Products in the database
# Product.objects.raw({}).delete()
for product in products:
insertProducts.append(Product(
name = product['name'],
description = product['description'],
categories = product['categories'],
quantity = 100,
createdAt = datetime.now(),
updatedAt = datetime.now()
))
# Product.objects.bulk_create(insertProducts)
with open('result.json') as file:
shop_data = json.load(file)
## Remove all Shops in the database
Shop.objects.raw({}).delete()
## Remove all Addresses in the database
Address.objects.raw({}).delete()
for shop_json in shop_data:
############
## Shops
############
# get the shops name
try:
shop_name = shop_json['name']
except(KeyError):
# skip if none exists
continue
# get the geolocation of a shop
# try:
# shop_location = {'type': 'Point', 'coordinates': [shop_json['latitude'], shop_json['longitude']]},
# except(KeyError):
# # skip if none exists
# continue
# assign all products to a shop
# shop_products = Product.objects.all(),
# assign empty address to shop
shop_address = None
### Create shop object
shop = Shop(
name = shop_name,
location = {'type': 'Point', 'coordinates': [shop_json['latitude'], shop_json['longitude']]},
products = insertProducts,
address = shop_address,
createdAt = datetime.now(),
updatedAt = datetime.now()
).save()
############
## Addresses
############
address_json = shop_json['address']
# get the address street name
try:
shop_address_street = address_json['address']
except(KeyError):
pass
# get the address post code
try:
shop_address_postcode = address_json['postalCode']
if(shop_address_postcode not in post_codes):
post_codes.append(shop_address_postcode)
except(KeyError):
pass
# get the address city
try:
shop_address_town = address_json['city']
if(shop_address_town not in cities):
cities.append(shop_address_town)
except(KeyError):
pass
# Create the address object while simultaneously setting the shop to the last created and updating the shops address
shop.address = Address(
shop = shop,
address = shop_address_street,
city = shop_address_town,
postCode = shop_address_postcode
).save()
shop.save()
break
end = datetime.now()
print('Ended: ', end)
print('The task lasted: ', (end-start))
print(
'In total there were ' + str(Shop.objects.raw({}).count()) + ' Shops to parse from our data.\n' +
'The Shops are listed in: ' + str(len(post_codes)) + ' postal codes.\n'
'The Shops are listed in: ' + str(len(cities)) + ' cities.'
)
if __name__ == "__main__":
main(sys.argv[1:])