Advertisement
Guest User

Untitled

a guest
May 24th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.42 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. import pandas as pd
  4. import numpy as np
  5. import MySQLdb as db
  6.  
  7. #!connection = db.connect(user='jaju15', passwd='hkw4AqEQzRPv', host = 'blu-ray.student.bth.se')
  8. #!c = connection.cursor()
  9.  
  10. def get_products_filtered(categories=None):
  11.     #df = pd.read_csv('data/Products.csv')
  12.     #if categories is not None:
  13.     #   for category in categories.keys():
  14.     #       df = df[df[category] == categories[category]]
  15.     #print categories
  16.     ''' SQL '''
  17.     connection = db.connect(user='jaju15', passwd='hkw4AqEQzRPv', db='jaju15', host='blu-ray.student.bth.se')
  18.     c = connection.cursor()
  19.     Overskrifter = ['color', 'gender' , 'brand', 'price', 'subtype', 'type', 'id', 'size' ]
  20.     c.execute(''' Call get_all_products()''')
  21.  
  22.     products = c.fetchall()
  23.  
  24.     rows = []
  25.  
  26.     for row in products:
  27.         dictionairy = {}
  28.         for i in range(len(Overskrifter)):
  29.             dictionairy[Overskrifter[i]] = row[i]
  30.  
  31.         rows.append(dictionairy)
  32.  
  33.  
  34.     if categories is not None:
  35.  
  36.         c.execute(''' Call get_filtered_products(%s,%s,%s)''',(categories['gender'], categories['type'], categories['subtype']))
  37.  
  38.         products = c.fetchall()
  39.  
  40.         rows = []
  41.  
  42.         for row in products:
  43.             dictionairy = {}
  44.             for i in range(len(Overskrifter)):
  45.                 dictionairy[Overskrifter[i]] = row[i]
  46.  
  47.             rows.append(dictionairy)
  48.  
  49.     return rows
  50.  
  51.  
  52.     #return df.to_dict('records')
  53.  
  54. def get_products_search(values):
  55.     #df = pd.read_csv('data/Products.csv')
  56.     #df = df[df['brand'].str.contains('(?i)' + '|'.join(values))]
  57.     ''' SQL '''
  58.     #print values
  59.     #print df.to_dict('records')
  60.     #return df.to_dict('records')
  61.  
  62.  
  63.     connection = db.connect(user='jaju15', passwd='hkw4AqEQzRPv', db='jaju15', host='blu-ray.student.bth.se')
  64.     c = connection.cursor()
  65.     value = ''
  66.     lastspot = len(values)
  67.     for i in range(len(values)):
  68.         if i == (lastspot-1):
  69.             value = value + values[i]
  70.  
  71.         else :
  72.             value =value + values[i] +' '
  73.  
  74.  
  75.  
  76.  
  77.     c.execute(''' Call search_product(%s) ''',[value])
  78.     products = c.fetchall ()
  79.  
  80.  
  81.     rows = []
  82.     Overskrifter = ['color', 'gender' , 'brand', 'price', 'subtype', 'type', 'id', 'size' ]
  83.  
  84.     for row in products:
  85.         dictionairy = {}
  86.         for i in range(len(Overskrifter)):
  87.             dictionairy[Overskrifter[i]] = row[i]
  88.  
  89.         rows.append(dictionairy)
  90.     print rows 
  91.  
  92.     return rows
  93.  
  94.  
  95.  
  96. def get_products_ids(ids):
  97.     #df = pd.read_csv('data/Products.csv')
  98.     #df = df.loc[df['id'].isin(ids)]
  99.     ''' SQL '''
  100.     print ids
  101.  
  102.     #return df.to_dict('records')
  103.  
  104.     connection = db.connect(user='jaju15', passwd='hkw4AqEQzRPv', db='jaju15', host='blu-ray.student.bth.se')
  105.     c = connection.cursor()
  106.     Overskrifter = ['color', 'gender' , 'brand', 'price', 'subtype', 'type', 'id', 'size' ]
  107.     idCorrect = []
  108.     count = 0
  109.  
  110.     for i in range(len(ids)):
  111.         insert = 1
  112.         for k in range(len(idCorrect)):
  113.             if ids[i] == (idCorrect[k]):
  114.                 insert = 0
  115.  
  116.         if insert == 0:
  117.             count = count +1
  118.  
  119.         if insert == 1:
  120.             idCorrect.append(ids[i])
  121.  
  122.     products = []
  123.     for i in range(len(idCorrect)):
  124.         c.execute(''' CALL get_product_ID(%d) ''' % idCorrect[i])
  125.         data = c.fetchone()
  126.         dictionairy = {}
  127.         for j in range(len(Overskrifter)):
  128.             dictionairy[Overskrifter[j]] = data[j]
  129.  
  130.         products.append(dictionairy)
  131.     print products
  132.     return products
  133.    
  134.  
  135.  
  136. def get_categories():
  137.     #df = pd.read_csv('data/Products.csv')
  138.     #genders = df['gender'].unique()
  139.     #types = [df[(df['gender'] == genders[0])]['type'].unique().tolist(), df[(df['gender'] == genders[1])]['type'].unique().tolist()]
  140.     #children = [[{'url': '', 'name': name} for name in types[0]],[{'url': '', 'name': name} for name in types[1]]]
  141.     ''' SQL '''
  142.  
  143.     #result = [{'title' : genders[0], 'children': children[0]}, {'title': genders[1], 'children': children[1]}]
  144.     #return result
  145.     connection = db.connect(user='jaju15', passwd='hkw4AqEQzRPv', db='jaju15', host='blu-ray.student.bth.se')
  146.     c = connection.cursor()
  147.  
  148.     c.execute(''' SELECT DISTINCT kon FROM konAlderPlagg where kon = 'herr' or kon = 'dam' ''')
  149.  
  150.     genders = []
  151.     genderrow = c.fetchall()
  152.     for genderrows in genderrow:
  153.         genders.append(genderrows[0])
  154.  
  155.  
  156.  
  157.     print genders
  158.  
  159.  
  160.     c.execute('''SELECT DISTINCT kon,overkategoriTyp from ((underKategori inner JOIN konAlderPlagg on underKategori.KonId = konAlderPlagg.idKonalder)
  161.     INNER JOIN overKategori on kategorid = overKategorid)''')
  162.     rowskategori = c.fetchall()
  163.  
  164.  
  165.     children =[]
  166.  
  167.  
  168.     result = [  {'title': genders[0], 'children' : []},
  169.                 {'title': genders[1], 'children': []}]
  170.  
  171.     for row in rowskategori:
  172.         if row[0] == genders[0]:
  173.             result[0]['children'].append({'url': '', 'name': row[1]})
  174.         if row[0] == genders[1]:
  175.             result[1]['children'].append({'url': '', 'name': row[1]})
  176.  
  177.     print result
  178.  
  179.     return result
  180. def get_subcategories(gender, category):
  181.     #df = pd.read_csv('data/Products.csv')
  182.     #types = df[(df['gender'] == gender) & (df['type'] == category)]['subtype'].unique().tolist()
  183.     #children = [{'url': '', 'name': name} for name in types]
  184.     #result = [{'gender' : gender, 'category': category, 'children': children}]
  185.  
  186.  
  187.    
  188.     ''' SQL '''
  189.     connection = db.connect(user='jaju15', passwd='hkw4AqEQzRPv', db='jaju15', host='blu-ray.student.bth.se')
  190.     c = connection.cursor()
  191.     c.execute(''' CALL get_subcategories(%s, %s) ''', (gender, category))
  192.     rows = c.fetchall()
  193.  
  194.     children = []
  195.     for row in rows:
  196.  
  197.         children.append({'url': '', 'name': row[0]})
  198.  
  199.     result = [{'gender' : gender, 'category': category, 'children': children}]
  200.  
  201.  
  202.  
  203.     return result
  204.  
  205. def write_order(order):
  206.   df_orders = pd.read_csv('data/Orders.csv')
  207.   # Get new order ID
  208.   #orderID = df_orders['orderid'].max() + 1
  209.   # Grab the products id number and the amount of each product
  210.   item_ids = list(map(int, order['items'].strip('[]').split(',')))
  211.   items = [{'id': int(x), 'amount': item_ids.count(x)} for x in list(set(item_ids))]
  212.  
  213.   # Get the name and so on for the customer.
  214.   firstname, lastname = order['name'].split()
  215.   email = order['email']
  216.   address = order['address']
  217.   zipcode = order['zipcode']
  218.   town = order['town']
  219.  
  220.   # Write the actual order
  221.   #df_products = pd.read_csv('data/Products.csv')
  222.   #for item in items:
  223.    # product = df_products[df_products['id'] == item['id']].to_dict('records')[0]
  224.     #df_orders.loc[len(df_orders)] = [orderID, firstname, lastname, address, town, zipcode, product['id'], product['brand'], product['type'], product['subtype'], product['color'], product['gender'], product['price'], product['size'], item['amount']]
  225.   #df_orders.to_csv('data/Orders.csv', index=False)
  226.  
  227.     #connection = db.connect(user='jaju15', passwd='hkw4AqEQzRPv', db='jaju15', host='blu-ray.student.bth.se')
  228.  
  229.  
  230.     #c = connection.cursor()
  231.  
  232.     #c.execute (''' CALL CreateCustomer(%s,%s,%s,%d,%s) ''',(firstname,lastname,address,zipcode,email))
  233.     #c.execute(''' SELECT max(KundId) FROM kunder ''')
  234.     #KundId = c.fetchone
  235.     #c.execute('''skapaorder(%d) ''', KundId)
  236.     #c.execute(''' SELECT max(orderid) FROM Ordrar ''')
  237.     #OrderId = c.fetchone
  238.     #for item in items
  239.     #   c.execute('''InsertOrderlista(%d,%d,%d) ''',(orderid,item['id'], item['amount']))
  240.  
  241.     #c.execute(''' Call UpdateOrder(%s)''', OrderId)
  242.  
  243.  
  244.  
  245.  
  246.  
  247.     #connection.commit()
  248.  
  249. def get_20_most_popular():
  250.     # Group by article # and sum of amount in Orders.
  251.     # grab the top 20 from Products and return as dict
  252.     #df = pd.read_csv('data/Orders.csv')
  253.     #op20_ids = df.groupby(['id']).sum().loc[:,['amount']].sort_values('amount', ascending=False).iloc[:20].index.tolist()
  254.     #df = pd.read_csv('data/Products.csv')
  255.     connection = db.connect(user='jaju15', passwd='hkw4AqEQzRPv', db='jaju15', host='blu-ray.student.bth.se')
  256.  
  257.  
  258.     c = connection.cursor()
  259.  
  260.     c.execute (''' CALL get_20_most_popular() ''')
  261.     popular = c.fetchall()
  262.     print popular
  263.     Overskrifter = ['color', 'gender' , 'brand', 'price', 'subtype', 'type', 'id', 'size' ]
  264.     rows = []
  265.     for row in popular:
  266.         dictionairy = {}
  267.         for i in range(len(Overskrifter)):
  268.             dictionairy[Overskrifter[i]] = row[i]
  269.  
  270.         rows.append(dictionairy)
  271.  
  272.     return rows
  273.    
  274.  
  275.  
  276. def main():
  277.  
  278.     #test = get_products_filtered({'color': 'Red', 'brand': 'WESC', 'price': 1599, 'size': 'XS'})
  279.     #test = get_products_filtered({'type': 'Bags', 'subtype': 'Leather bag'})
  280.     #test = get_products_search(['Red', 'Jack and Jones'])
  281.     #print(get_categories())
  282.     #print(get_subcategories('Female', 'Bags'))
  283.     print(get_20_most_popular())
  284.     #write_order({'town': 'asad', 'name': 'asd asd', 'items': '[2160,2160,2160,2160,2160,2160,2160,2160,2160]', 'zipcode': '123123', 'address': 'asd', 'email': 'asd'})
  285.     #test = get_products_search(['jack', 'and', 'jones'])
  286.     #print(test)
  287.     #print (my_get_most_popular())
  288.  
  289. if _name_ == '_main_':
  290.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement