· 6 years ago · Nov 26, 2019, 04:14 AM
1import xml.etree.ElementTree as etree
2from slugify import slugify
3import pymysql
4
5tree = etree.parse('index_cron.xml')
6shop_tag = tree.find('shop')
7offers_tag = shop_tag.find('offers')
8# # print(f'В XML %s офферов' %len(offers_tag))
9offer_tag = offers_tag.findall('offer')
10
11db = pymysql.connect(
12 host='localhost',
13 user='root',
14 password='731731731',
15 db='MYSQL',
16 charset='utf8mb4',
17 port=3307
18)
19
20db_name = input('Введите название БД') or 'test'
21
22with db.cursor() as cursor:
23 def create_db(name):
24 cursor.execute('CREATE DATABASE IF NOT EXISTS `%s`' % name)
25 cursor.execute('USE `%s`' % name)
26
27
28 create_db(db_name)
29
30
31 def create_table_sf():
32 cursor.execute('''
33 CREATE TABLE IF NOT EXISTS `system_files` (
34 `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
35 `disk_name` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci',
36 `file_name` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci',
37 `file_size` INT NOT NULL,
38 `content_type` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci',
39 `title` VARCHAR(191) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
40 `description` TEXT NULL COLLATE 'utf8mb4_unicode_ci',
41 `field` VARCHAR(191) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
42 `attachment_id` VARCHAR(191) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
43 `attachment_type` VARCHAR(191) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
44 `is_public` TINYINT NOT NULL DEFAULT '1',
45 `sort_order` INT NULL DEFAULT NULL,
46 `created_at` TIMESTAMP NULL DEFAULT NULL,
47 `updated_at` TIMESTAMP NULL DEFAULT NULL,
48 PRIMARY KEY (`id`),
49 INDEX `system_files_field_index` (`field`),
50 INDEX `system_files_attachment_id_index` (`attachment_id`),
51 INDEX `system_files_attachment_type_index` (`attachment_type`)
52 )
53 COLLATE='utf8mb4_unicode_ci'
54 ENGINE=InnoDB
55 AUTO_INCREMENT=309
56 ''')
57
58
59 def create_table_brands():
60 cursor.execute('''
61 CREATE TABLE IF NOT EXISTS `xl1034_shop_brands` (
62 `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
63 `name` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci',
64 `description` TEXT NULL COLLATE 'utf8mb4_unicode_ci',
65 `slug` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci',
66 `logotype` VARCHAR(191) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci'
67 )
68 COLLATE='utf8mb4_unicode_ci'
69 ENGINE=InnoDB
70 AUTO_INCREMENT=24
71 ''')
72
73
74 def create_table_cat():
75 cursor.execute('''
76 CREATE TABLE IF NOT EXISTS `xl1034_shop_categories` (
77 `id` INT UNSIGNED NOT NULL,
78 `name` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci',
79 `description` TEXT NULL COLLATE 'utf8mb4_unicode_ci',
80 `keywords` TEXT NULL COLLATE 'utf8mb4_unicode_ci',
81 `slug` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci',
82 `parent_id` INT NULL DEFAULT NULL,
83 `nest_left` INT NULL DEFAULT NULL,
84 `nest_right` INT NULL DEFAULT NULL,
85 `nest_depth` INT NULL DEFAULT NULL,
86 PRIMARY KEY (`id`)
87 )
88 COLLATE='utf8mb4_unicode_ci'
89 ENGINE=InnoDB
90 ''')
91
92
93 def create_table_cat_prod():
94 cursor.execute('''
95 CREATE TABLE IF NOT EXISTS `xl1034_shop_category_product` (
96 `category_id` INT UNSIGNED NOT NULL,
97 `product_id` INT UNSIGNED NOT NULL,
98 PRIMARY KEY (`category_id`, `product_id`)
99 )
100 COLLATE='utf8mb4_unicode_ci'
101 ENGINE=InnoDB
102 ''')
103
104
105 def create_table_curr():
106 cursor.execute('''
107 CREATE TABLE IF NOT EXISTS `xl1034_shop_currencies` (
108 `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
109 `code` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci',
110 `name` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci',
111 `is_default` TINYINT NOT NULL DEFAULT '0',
112 `rate` DOUBLE NOT NULL DEFAULT '1',
113 `sign` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci',
114 `is_prefix` TINYINT NOT NULL DEFAULT '0',
115 PRIMARY KEY (`id`)
116 )
117 COLLATE='utf8mb4_unicode_ci'
118 ENGINE=InnoDB
119 ''')
120
121
122 def create_table_param():
123 cursor.execute('''
124 CREATE TABLE IF NOT EXISTS `xl1034_shop_parameters` (
125 `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
126 `name` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci',
127 PRIMARY KEY (`id`)
128 )
129 COLLATE='utf8mb4_unicode_ci'
130 ENGINE=InnoDB
131 AUTO_INCREMENT=123
132 ''')
133
134
135 def create_table_param_prod():
136 cursor.execute('''
137 CREATE TABLE IF NOT EXISTS `xl1034_shop_parameter_product` (
138 `parameter_id` INT UNSIGNED NOT NULL,
139 `product_id` INT UNSIGNED NOT NULL,
140 `value` TEXT NULL COLLATE 'utf8mb4_unicode_ci',
141 PRIMARY KEY (`parameter_id`, `product_id`)
142 )
143 COLLATE='utf8mb4_unicode_ci'
144 ENGINE=InnoDB
145 ''')
146
147
148 def create_table_prod():
149 cursor.execute('''
150 CREATE TABLE IF NOT EXISTS `xl1034_shop_products` (
151 `id` INT UNSIGNED NOT NULL,
152 `brand_id` INT NULL DEFAULT NULL,
153 `name` TEXT NOT NULL COLLATE 'utf8mb4_unicode_ci',
154 `slug` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci',
155 `sku` VARCHAR(191) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
156 `price` DOUBLE NOT NULL,
157 `purchase_price` DOUBLE NOT NULL,
158 `description` VARCHAR(191) NULL COLLATE 'utf8mb4_unicode_ci',
159 `video_code` VARCHAR(191) NULL COLLATE 'utf8mb4_unicode_ci',
160 `currency_id` INT NOT NULL,
161 `available` TINYINT NOT NULL DEFAULT '0',
162 `created_at` TIMESTAMP NULL DEFAULT NOW(),
163 `updated_at` TIMESTAMP NULL DEFAULT NOW()
164 )
165 COLLATE='utf8mb4_unicode_ci'
166 ENGINE=InnoDB
167 ''')
168
169
170 # create_table_sf()
171 create_table_brands()
172 # create_table_cat()
173 # create_table_cat_prod()
174 create_table_curr()
175 # create_table_param()
176 # create_table_param_prod()
177 create_table_prod()
178
179
180 # def insert_brands():
181 #
182 # l_o = 0
183 # """Заполнение таблицы xl1034_shop_BRANDS"""
184 # n = []
185 #
186 # while l_o != len(offers_tag):
187 # offer_vendor_tag = offer_tag[l_o].find('vendor')
188 #
189 # slug_offer_vendor_tag = offer_vendor_tag.text
190 #
191 # n.append(slug_offer_vendor_tag)
192 #
193 # # cursor.execute('''
194 # # INSERT INTO `xl1034_shop_BRANDS` (name, slug) VALUES ("%s", "%s")
195 # # ''' % (slug_offer_vendor_tag, sovt))
196 # # db.commit()
197 #
198 # l_o += 1
199 #
200 # b_name = list(set(n))
201 # len_b_name = 0
202 #
203 # while len_b_name != len(b_name):
204 # sovt = slugify(b_name[len_b_name])
205 # cursor.execute('''
206 # INSERT INTO `xl1034_shop_BRANDS` (name, slug) VALUES ("%s", "%s")
207 # ''' % (b_name[len_b_name], sovt))
208 #
209 # db.commit()
210 # len_b_name += 1
211 #
212 #
213 # insert_brands()
214
215 # Дальше начал бы крутить офферс и на каждой итерации делал бы следующие вещи:
216 #
217 # Получить id
218 # Получить available
219 # Получить name
220 # Получить sku
221 # Получить price
222 # Получить purchase_price
223 # Получить description
224 # Получить video_code
225 #
226 # Далее, по vendor'у сделать запрос в таблицу brands, и если такой бренд есть, то забрать оттуда его id, если нет, то создать такой бренд и забрать его id.
227 #
228 # После забираем картинки, и крутим их в цикле,
229 # Проверяем в system_files по имени и attachment_id (он должен быть равен offer id), если такой записи нет, то качаем файл, кладём в папочку и делаем запись в system_files.
230 #
231 # Удаляем из category_product все записи, где product_id == offer_id
232 #
233 # Далее проходимся по параметрам с param name="Категория" и делаем следующее:
234 #
235 # - Вставляем в category_product значение парама и offer_id
236 #
237 # Та же тема с остальными параметрами
238 #
239 # Идём по параметрам, если param name != 'Категория', то
240 # По имени забираем из parameters ИД параметра (если не находим, то создаём новый и берём его id)
241 # И в parameter_product пишем
242 # ИД Параметра, ИД Оффера, Значение
243
244 # def insert_curr():
245
246
247
248
249
250
251 def test():
252
253
254 l_s = 0
255 currencies_tag = shop_tag.find('currencies')
256 currency_tag = currencies_tag.findall('currency')
257
258 if l_s == 0:
259 '''Очистить xl1034_shop_products иначе оно чет записывает еще 100(в данном случае) записей
260 Потом сделаю нормально'''
261 cursor.execute('DELETE FROM `xl1034_shop_currencies`')
262
263 while l_s != len(currency_tag):
264
265 id_attr = currency_tag[l_s].get('id')
266
267 if id_attr == 'RUB':
268 curr_name = 'Рубли'
269 code = 'rub'
270 sign = 'руб.'
271 is_default = 1
272
273 rate_attr = currency_tag[l_s].get('rate')
274
275 curr_check = cursor.execute(
276 'SELECT `id`, `rate` FROM `xl1034_shop_currencies` WHERE `rate` = "%s"' % rate_attr)
277
278 if curr_check == 0:
279 cursor.execute('''INSERT INTO `xl1034_shop_currencies` (`code`, `name`, `is_default`, `rate`, `sign`)
280 VALUES ("%s", "%s", "%s", "%s", "%s")''' %(code, curr_name, is_default, rate_attr, sign))
281 db.commit()
282 cursor.execute(
283 'SELECT `id`, `rate` FROM `xl1034_shop_currencies` WHERE `rate` = "%s"' % rate_attr)
284 currency_id = int(cursor.fetchone()[1])
285 else:
286 currency_id = int(cursor.fetchone()[1])
287
288
289 l_s +=1
290
291
292
293 l_o = 0
294 n = []
295 if l_o == 0:
296 '''Очистить xl1034_shop_products иначе оно чет записывает еще 100(в данном случае) записей
297 Потом сделаю нормально'''
298 cursor.execute('DELETE FROM `xl1034_shop_products`')
299
300 while l_o != len(offers_tag):
301
302 id_tag = offer_tag[l_o].get('id')
303 if offer_tag[l_o].get('available') == 'true':
304 available = 1
305 else:
306 available = 0
307
308 offer_name_tag = offer_tag[l_o].find('name').text
309 slug = slugify(offer_name_tag)
310
311 offer_sku_tag = offer_tag[l_o].find('vendorCode').text
312 offer_price_tag = offer_tag[l_o].find('price').text
313
314 offer_price_p_tag = offer_tag[l_o].find('purchase_price').text
315 offer_description_tag = offer_tag[l_o].find('description').text
316 # print(offer_description_tag)
317
318 try:
319 # Не во всех офферах есть видео
320 offer_video_tag = offer_tag[l_o].find('video')
321 video_code_tag = offer_video_tag.text
322 except:
323 video_code_tag = None
324
325
326 # cursor.execute('''
327 # INSERT INTO `xl1034_shop_products` (`id`, `brand_id`, `name`, `slug`, `sku`, `price`,
328 # `purchase_price`, `currency_id`, `available` )
329 # VALUES ("%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s")
330 # ''' % (id_tag,
331 # brand_id,
332 # offer_name_tag,
333 # slug,
334 # offer_sku_tag,
335 # offer_price_tag,
336 # offer_price_p_tag,
337 # # offer_description_tag,
338 # # video_code_tag,
339 # currency_id,
340 # available
341 # )
342 # )
343 # db.commit()
344
345 # Далее, по vendor'у сделать запрос в таблицу brands, и если такой бренд есть, то забрать оттуда его id, если нет, то создать такой бренд и забрать его id.
346
347
348 offer_vendor_tag = offer_tag[l_o].find('vendor').text
349
350 id_check = cursor.execute(
351 'SELECT `id`, `name` FROM `xl1034_shop_brands` WHERE `name` = "%s"' % offer_vendor_tag)
352 if id_check == 0:
353 cursor.execute('''
354 INSERT INTO `xl1034_shop_brands` (`name`, `slug`)
355 VALUES ("%s", "%s")
356 '''
357 %(offer_vendor_tag, slugify(offer_vendor_tag)))
358 db.commit()
359 cursor.execute(
360 'SELECT `id`, `name` FROM `xl1034_shop_brands` WHERE `name` = "%s"' % offer_vendor_tag)
361 brand_id = cursor.fetchone()[0] # Слабо понимаю почему, но без этой и двух строчек выше - не работает
362 else:
363 brand_id = cursor.fetchone()[0]
364
365
366
367
368 cursor.execute('''
369 INSERT INTO `xl1034_shop_products` (`id`, `brand_id`, `name`, `slug`, `sku`, `price`,
370 `purchase_price`, `currency_id`, `available` )
371 VALUES ("%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s")
372 ''' % (id_tag,
373 brand_id,
374 offer_name_tag,
375 slug,
376 offer_sku_tag,
377 offer_price_tag,
378 offer_price_p_tag,
379 # offer_description_tag,
380 # video_code_tag,
381 currency_id,
382 available
383 )
384 )
385 db.commit()
386
387
388 l_o += 1
389 #
390 # insert_curr()
391 test()