-
Notifications
You must be signed in to change notification settings - Fork 0
/
ptap.py
195 lines (181 loc) · 6.14 KB
/
ptap.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
import requests
import json
import sqlite3
from rq import Queue
from redis import Redis
from unidecode import unidecode
import logging
requests.packages.urllib3.disable_warnings()
logger = logging.getLogger('ptap')
logger.setLevel(logging.ERROR)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh = logging.FileHandler('ptap_errors.log')
fh.setFormatter(formatter)
logger.addHandler(fh)
logger.error("===========reloaded==============")
class PepperTap:
base_url = "https://api.peppertap.com"
# should be imported from database connection file
db_conn = sqlite3.connect('competitor_inventory_test1.db')
def clear_table_data(self):
self.db_cursor.execute(
"""
DELETE FROM peppertap_product
"""
)
self.db_cursor.execute(
"""
DELETE FROM peppertap_zone
"""
)
self.db_cursor.execute(
"""
DELETE FROM peppertap_zone_product_map
"""
)
def _get_cities(self):
cities_url = "/location/v1/cities/"
response = requests.get(
PepperTap.base_url + cities_url,
verify=False
)
self.cities = [
{'id': city['id'], 'name': city['name']}
for city in response.json()
]
def _get_areas(self):
zones_url = "/location/v1/areas/"
response = requests.get(
PepperTap.base_url + zones_url,
verify=False
)
self.areas = response.json()
def _write_zones(self):
zones = {}
for area in self.areas:
try:
zones[area['zone_id']]['city'] = area['city']
zones[area['zone_id']]['areas'].append(area['area'])
except KeyError:
zones[area['zone_id']] = {
'city': area['city'],
'areas': [area['area']]
}
self.zones = zones
for zone_id, values in zones.iteritems():
try:
self._insert_zone(
(
zone_id,
', '.join(values['areas']),
values['city']
)
)
except Exception as inst:
logger.error(
"{type}: {message}: {data}\n\t=====\n".format(
type=type(inst),
message=str(inst),
data=': '.join([str(zone_id), str(values)])
)
)
def _insert_zone(self, values):
insert_query = "INSERT INTO peppertap_zone VALUES (?, ?, ?)"
self.db_cursor.execute(
insert_query,
values
)
PepperTap.db_conn.commit()
def _insert_product(self, values):
insert_query = "INSERT INTO peppertap_product VALUES (?, ?, ?, ?, ?, ?, ?)"
self.db_cursor.execute(
insert_query,
values
)
PepperTap.db_conn.commit()
def _insert_product_zone_mapping(self, values):
insert_query = "INSERT INTO peppertap_zone_product_map VALUES (?, ?)"
self.db_cursor.execute(
insert_query,
values
)
PepperTap.db_conn.commit()
def _get_categories(self, zone_id):
categories_url = "/user/shop/categories/"
response = requests.get(
PepperTap.base_url + categories_url,
params={'zone_id': zone_id},
verify=False
)
return response.json()['categories']
def __init__(self, *args, **kwargs):
try:
import setup_db_ptap
except Exception as inst:
logger.error(
"{type}: {message}\n\t=====\n".format(
type=type(inst),
message=str(inst),
)
)
self.db_cursor = PepperTap.db_conn.cursor()
self._get_areas()
self._write_zones()
def get_products_by_category(self, category, zone_id):
products_url = "/user/shop/{cid}/products/"
params = {'zone_id': zone_id}
response = requests.get(
PepperTap.base_url + products_url.format(
cid=category['id']
),
params=params,
verify=False
)
products = response.json()['pl']
for product in products:
try:
self._insert_product(
(
product['ps'][0]['uid'],
product['ps'][0]['sp'],
product['ps'][0]['mrp'],
product['tle'],
", ".join(product['typ']),
category['name'],
product['ps'][0]['da'],
)
)
except Exception as inst:
logger.error(
"{type}: {message}: {data}\n\t=====\n".format(
type=type(inst),
message=str(inst),
data=str(product)
)
)
try:
self._insert_product_zone_mapping(
(
zone_id,
product['ps'][0]['uid'],
)
)
except Exception as inst:
logger.error(
"{type}: {message}: {data}\n\t=====\n".format(
type=type(inst),
message=str(inst),
data="product uid {}, zone_id {}".format(
product['ps'][0]['uid'], zone_id
)
)
)
def get_products_by_zone(self, zone_id):
categories = self._get_categories(zone_id)
for category in categories:
for child_category in category['children']:
# should be pushing this to the task queue
self.get_products_by_category(child_category, zone_id)
def get_all_products(self):
for zone_id in self.zones.keys():
self.get_products_by_zone(zone_id)