forked from SR-11-2021-10/Backend-SR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrud.py
66 lines (59 loc) · 2.05 KB
/
crud.py
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""
Here, we are going to implement the logic to handle operations on the DB
This CRUD function will be use on the view (endpoints) implementation
"""
from fastapi import HTTPException
from sqlalchemy.orm import Session
from db import models
from sr.model import RecommenderSystem
import pandas as pd
import schemas
import hashlib
# Hash plain text password
def hash_plain_password(password: str) -> str:
return hashlib.sha1(bytes(password, "UTF-8")).hexdigest()
# Get user's data only if the password provided is correct
def login_user(db: Session, user: schemas.UserAuth):
# Retrieve the user
query_user = (
db.query(models.User).filter(models.User.username == user.username).first()
)
if query_user is None:
# User does not exist
raise HTTPException(
status_code=404, detail=f"User: {user.username} does not exist !"
)
else:
hashed_pass = hash_plain_password(user.password)
user_pass = query_user.hashed_password
if user_pass != hashed_pass:
raise HTTPException(status_code=403, detail="Wrong password")
else:
return query_user
def create_user(db: Session, user: schemas.UserAuth):
hash_password = hash_plain_password(user.password)
# New instance of User
db_user = models.User(username=user.username, hashed_password=hash_password)
# Create new user
db.add(db_user)
# Commit transaction
db.commit()
# Get created user with ID to send into response
db.refresh(db_user)
return db_user
def make_recommendation(
data: pd.DataFrame, recommendation: schemas.Recommendation, artist: pd.DataFrame
):
# Create the recommendation model
rs = RecommenderSystem(
type=recommendation.type,
similitude=recommendation.similitude,
user_item_rating=data,
)
try:
prediction = rs.predict(
uid=recommendation.username, iid=recommendation.artist, artist=artist
)
return prediction
except Exception as e:
raise HTTPException(status_code=500, detail=e)