Example #1
0
def main():
    """
    Main part
    """

    ### Create Databases and tables ###

    cnx = mysql.connector.connect(user=USER, password=PASSWORD,host=HOST)
    cursor = cnx.cursor()

    create_db(cursor, cnx)
    populate_tables(cursor)

    ### Fetch the data from the API ###

    api_manager = ApiManager()
    categories = api_manager.categories()

    for category in categories:
        if category['products'] > MIN_PRODUCTS_PER_CATEGORY:

            ### Category ###
            cursor.execute("INSERT INTO `category` (name, url, tag) VALUES (%s, %s, %s)"
            ,(category['name'], category['url'], category['id']))
            category_index = cursor.lastrowid
            print("Category added ")
            cnx.commit()

            ### Products ###
            products = api_manager.category_products(category['id'])
            for product in products:
                try:
                    print(product['product_name'])
                    cursor.execute("INSERT INTO `product` (name, description, stores, grade, link, fat, sugars, salt, saturated_fat) \
                    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)", (product['product_name'], product['generic_name_fr'], product['stores'], \
                    product['nutrition_grades'], product['link'], product['nutrient_levels']['fat'], product['nutrient_levels']['sugars'], \
                    product['nutrient_levels']['salt'], product['nutrient_levels']['saturated-fat']))
                    product_index = cursor.lastrowid
                except KeyError:
                    pass
                print("Product added ")
                cnx.commit()

                ### Mutual table ###
                cursor.execute("INSERT INTO `categories_products` (category_id, product_id) \
                VALUES (%s, %s)", (category_index, product_index))