forked from AIGroupProjectGPAI2/MasterRepository
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhuw_recommend.py
More file actions
40 lines (34 loc) · 1.58 KB
/
huw_recommend.py
File metadata and controls
40 lines (34 loc) · 1.58 KB
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
from flask import Flask, request, session, render_template, redirect, url_for, g
from flask_restful import Api, Resource, reqparse
import os
from pymongo import MongoClient
from dotenv import load_dotenv
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 = MongoClient(dbstring.format(*envvals))
else:
client = MongoClient()
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):
""" 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)))
return prodids, 200
# This method binds the Recom class to the REST API, to parse specifically
# requests in the format described below.
api.add_resource(Recom, "/<string:profileid>/<int:count>")