app = Flask(__name__) api = Api(app) # We define these variables to (optionally) connect to an external MongoDB # instance. envvals = ["MONGODBUSER", "MONGODBPASSWORD", "MONGODBSERVER"] dbstring = 'mongodb+srv://{0}:{1}@{2}/test?retryWrites=true&w=majority' # Since we are asked to pass a class rather than an instance of the class to the # add_resource method, we open the connection to the database outside of the # Recom class. load_dotenv() if os.getenv(envvals[0]) is not None: envvals = list(map(lambda x: str(os.getenv(x)), envvals)) client = createConnectionMongoDB() else: client = createConnectionMongoDB() database = client.huwebshop class Recom(Resource): """ This class represents the REST API that provides the recommendations for the webshop. At the moment, the API simply returns a random set of products to recommend.""" def get(self, profileid, count, type, productid): """ This function represents the handler for GET requests coming in through the API. It currently returns a random sample of products. """ # randcursor = database.products.aggregate([{'$sample': {'size': count}}]) # prodids = list(map(lambda x: x['_id'], list(randcursor))) prodids = []
import csv import os from dotenv import load_dotenv, find_dotenv from database.connection import createConnectionMongoDB load_dotenv(dotenv_path=find_dotenv(), verbose=True) database = createConnectionMongoDB() file = open(os.path.dirname(os.path.abspath(__file__)) + "/csv/sub_category.csv", "w+", encoding="utf-8") data = database.sessions.find() with file: fnames = ['session_id', 'views', 'sub_gategory_name' ] writer = csv.DictWriter(file, fieldnames=fnames, delimiter='#') print('Started creating viewed_sub_gategory.csv') for item in data: try: sub_categories = item['preferences']['sub_category'] for sub_category in sub_categories: lineDic = {} try: lineDic.update({'session_id': item['_id']}) except KeyError: lineDic.update({'session_id': None}) try:
import csv import os from dotenv import load_dotenv, find_dotenv from database.connection import createConnectionMongoDB load_dotenv(dotenv_path=find_dotenv(), verbose=True) database = createConnectionMongoDB().huwebshop file = open(os.path.dirname(os.path.abspath(__file__)) + "/csv/viewed_brand.csv", "w+", encoding="utf-8") data = database.sessions.find() with file: fnames = ['session_id', 'views', 'brand_name'] writer = csv.DictWriter(file, fieldnames=fnames, delimiter='#') print('Started creating viewed_brand.csv') for item in data: try: brands = item['preferences']['brand'] for brand in brands: lineDic = {} try: lineDic.update({'session_id': item['_id']}) except KeyError: lineDic.update({'session_id': None})
def __init__(self, app): """ Within this constructor, we establish a connection with the database and perform necessary setup of the database (if applicable) and menu.""" self.app = app # Depending on whether environment variables have been set, we connect # to a local or remote instance of MongoDB, and a default or non-default # external recommendation service. load_dotenv() envdict = {} if os.getenv(self.envvals[0]) is not None: for val in self.envvals: envdict[val] = str(os.getenv(val)) if envdict["MONGODBUSER"] and envdict["MONGODBPASSWORD"] and envdict["MONGODBSERVER"]: self.client = createConnectionMongoDB() else: self.client = createConnectionMongoDB() if envdict["RECOMADDRESS"]: self.recseraddress = envdict["RECOMADDRESS"] else: self.client = createConnectionMongoDB() self.database = self.client.huwebshop # Once we have a connection to the database, we check to see whether it # has a category index prepared; if not, we have a function to make it. if "categoryindex" not in self.database.list_collection_names() or self.database.categoryindex.count_documents({}) == 0: self.createcategoryindex() # We retrieve the categoryindex from the database when it is set. self.categoryindex = self.database.categoryindex.find_one({}, {'_id' : 0}) # In order to save time in future, we flatten the category index once, # and translate all values to and from an encoded, URL-friendly, legible # format. catlist = self.flattendict(self.categoryindex) for cat in catlist: enc_cat = self.encodecategory(cat) self.catencode[cat] = enc_cat self.catdecode[enc_cat] = cat # Since the main menu can't show all the category options at once in a # legible manner, we choose to display a set number with the greatest # number of associated products. countlist = list(map(lambda x, y: (y['_count'], x), self.categoryindex.keys(), self.categoryindex.values())) countlist.sort(reverse=True) self.mainmenuitems = [x[1] for x in countlist[0:self.mainmenucount]] # Finally, we here attach URL rules to all pages we wish to render, to # make the code self-contained; although the more common decorators do # the same thing, we wish to have this class contain as much logic as # possible. self.app.before_request(self.checksession) self.app.add_url_rule('/', 'index', self.renderpackettemplate) self.app.add_url_rule('/producten/', 'producten-0', self.productpage) self.app.add_url_rule('/producten/<cat1>/', 'producten-1', self.productpage) self.app.add_url_rule('/producten/<cat1>/<cat2>/', 'producten-2', self.productpage) self.app.add_url_rule('/producten/<cat1>/<cat2>/<cat3>/', 'producten-3', self.productpage) self.app.add_url_rule('/producten/<int:page>/', 'producten-4', self.productpage) self.app.add_url_rule('/producten/<cat1>/<int:page>/', 'producten-5', self.productpage) self.app.add_url_rule('/producten/<cat1>/<cat2>/<int:page>/', 'producten-6', self.productpage) self.app.add_url_rule('/producten/<cat1>/<cat2>/<cat3>/<int:page>/', 'producten-7', self.productpage) self.app.add_url_rule('/producten/<cat1>/<cat2>/<cat3>/<cat4>/<int:page>/', 'producten-8', self.productpage) self.app.add_url_rule('/productdetail/<productid>/', 'productdetail', self.productdetail) self.app.add_url_rule('/winkelmand/', 'winkelmand', self.shoppingcart) self.app.add_url_rule('/categorieoverzicht/', 'categorieoverzicht', self.categoryoverview) self.app.add_url_rule('/change-profile-id', 'profielid', self.changeprofileid, methods=['POST']) self.app.add_url_rule('/add-to-shopping-cart', 'toevoegenaanwinkelmand', self.addtoshoppingcart, methods=['POST']) self.app.add_url_rule('/producten/pagination-change', 'aantalperpaginaaanpassen', self.changepaginationcount, methods=['POST'])
from database.connection import createConnectionMysqlDB, createConnectionMysqlDBREC, createConnectionMongoDB import os, csv from sqlalchemy.sql import select from engine.migrations.create_trend_recommendations import Trend from engine.migrations.create_terms_table import Terms from database.migrations.create_products_table import Products recDB = createConnectionMysqlDBREC().connect() dataDB = createConnectionMysqlDB().connect() mongoDB = createConnectionMongoDB().huwebshop def prepproduct(p): """ This helper function flattens and rationalizes the values retrieved for a product block element. """ r = {} r['name'] = p['name'] r['price'] = p['price']['selling_price'] r['price'] = str( r['price'])[0:-2] + ",-" if r['price'] % 100 == 0 else str( r['price'])[0:-2] + "," + str(r['price'])[-2:] if r['price'][0:1] == ",": r['price'] = "0" + r['price'] if p['properties']['discount'] is not None: r['discount'] = p['properties']['discount'] r['smallimage'] = "" # TODO: replace this with actual images! r['bigimage'] = "" # TODO: replace this with actual images! r['id'] = p['_id'] return r