Skip to content

Instantly share code, notes, and snippets.

@ciaranmccormick
Created August 11, 2015 12:33
Show Gist options
  • Save ciaranmccormick/bdacc6f8e8ff8adfacec to your computer and use it in GitHub Desktop.
Save ciaranmccormick/bdacc6f8e8ff8adfacec to your computer and use it in GitHub Desktop.
from .tesco_api import TescoRequestClient
from .models import TescoProduct
def insert_basket():
# create Tesco Request Client
client = TescoRequestClient(email, password, dev_app, app_key)
products = client.format() # See note in tesco_api.py about this function name
for product in products:
# insert product into database
product_id = product.pop('product_id')
obj, created = TescoProduct.objects.get_or_create(product_id=product_id, defaults=product)
if created:
print("New product created")
class TescoRequestClient:
# __init__ is used to create TescoRequestClient object. Request client is an object that allows us to make
# requests to tesco it should not hold any product info
def __init__(self, email, password, dev_key, app_key):
self.session_key = self.login(email, password, dev_key, app_key)
self.basket_items_ids = self.get_basket() # Don't store the basket here
self.all_product_data = self.format() # Don't store the products here
def req(self, params):
r = requests.get("https://secure.techfortesco.com/tescolabsapi/restservice.aspx", params=params)
r = r.json() if r.status_code == 200 else "fail"
return dict(r)
def login(self, email, password, dev_key, app_key):
params = {
"Command": "LOGIN",
"Email": email,
"Password": password,
"Developerkey": dev_key,
"Applicationkey": app_key,
}
login_details = self.req(params)
return login_details['SessionKey']
def search(self, search_text, extended):
params = {
"Command": "PRODUCTSEARCH",
"SearchText": search_text,
"SessionKey": self.session_key,
"ExtendedInfo": "Y" if extended else "N"
}
r = self.req(params)
return r
def get_basket(self):
basket_items_ids = list()
params = {
"Command": "LISTBASKET",
"SessionKey": self.session_key
}
for item in self.req(params)['BasketLines']:
basket_items_ids.append(int(item['ProductId'].strip("u")))
return basket_items_ids
def edit_basket(self, product_id, q):
while not(re.search('-[0-9]*|[0-9]', str(q))):
q = input("Please select quantity (pos int for add, neg int for rm)")
params = {
"Command": "CHANGEBASKET",
"SessionKey": self.session_key,
"ChangeQuantity": int(q),
"ProductId": product_id,
}
r = self.req(params)
return r['StatusInfo']
def extract(self, place, regex='(?<=.)*[0-9]+(?=([ ]|)[gG])(?=.)*'):
obj = re.search(regex, place)
return float(obj.group(0)) if obj and obj.group(0).isdigit() else (obj.group() if obj else "False")
# Change the name of the this function format is a built in function (check the IDE for this error)
def format(self):
biids = self.basket_items_ids
product_data = list()
for x in biids:
print x
info = {"energy": 0, "fat": 0, "saturates": 0, "carbohydrate": 0, "sugar": 0, "protein": 0, "fibre": 0}
params = {
"Command": "PRODUCTSEARCH",
"SessionKey": self.session_key,
"SearchText": int(x),
"ExtendedInfo": "Y",
}
p = self.req(params)['Products'][0]
if "Nutrients" in p.keys():
for nutrient in p['Nutrients']:
for kword in info:
nutri_name = re.search('(?<=.)*' + kword + r'(?=.)*', nutrient['NutrientName'], flags=re.IGNORECASE)
if nutri_name:
info[str(nutri_name.group(0).lower()).strip("u")] = float(re.search('[0-9]*((\.)[0-9]*|)', nutrient['SampleSize']).group(0))
# info["portion_size"] = self.extract(p['Nutrients'][0]['ServingDescription'])
# info["per_unit_weight"] = self.extract(p['Nutrients'][0]['SampleDescription'])
# commented out as I now realise that these apply to a lot less products than I originally realised
info["product_name"] = str(p['Name']).strip("u")
info["product_id"] = int(str(p['ProductId']).strip("u"))
info["peodprice"] = self.extract(str(p['Price']), '[0-9]*((\.)[0-9]*|)')
product_data.append(info)
return product_data
def make_products(self):
for product in self.all_product_data: # all_product_data is the list of dictionaries with the product data
print product
# Product is a dictionary containing the data for one single product
# I was hoping to be able to pass the dictionary of products into
create_tesco_product(product)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment