Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions server/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
FROM python:3.12.0-slim-bookworm

ENV PYTHONBUFFERED 1
ENV PYTHONWRITEBYTECODE 1

ENV APP=/app

# Change the workdir.
WORKDIR $APP

# Install the requirements
COPY requirements.txt $APP

RUN pip3 install -r requirements.txt

# Copy the rest of the files
COPY . $APP

EXPOSE 8000

RUN chmod +x /app/entrypoint.sh

ENTRYPOINT ["/bin/bash","/app/entrypoint.sh"]

CMD ["gunicorn", "--bind", ":8000", "--workers", "3", "djangoproj.wsgi"]
27 changes: 24 additions & 3 deletions server/database/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ app.get('/fetchReviews', async (req, res) => {
const documents = await Reviews.find();
res.json(documents);
} catch (error) {
res.status(500).json({ error: 'Error fetching documents' });
res.status(500).json({ error: 'Error fetching all reviews' });
}
});

Expand All @@ -52,23 +52,44 @@ app.get('/fetchReviews/dealer/:id', async (req, res) => {
const documents = await Reviews.find({dealership: req.params.id});
res.json(documents);
} catch (error) {
res.status(500).json({ error: 'Error fetching documents' });
res.status(500).json({ error: 'Error fetching reviews by dealership' });
}
});

// Express route to fetch all dealerships
app.get('/fetchDealers', async (req, res) => {
//Write your code here
try {
const documents = await Dealerships.find();
res.json(documents);
} catch (error) {
res.status(500).json({ error: 'Error fetching all dealerships' });
}
});

// Express route to fetch Dealers by a particular state
app.get('/fetchDealers/:state', async (req, res) => {
//Write your code here
try {
const documents = await Dealerships.find({state: req.params.state});
res.json(documents);
} catch (error) {
res.status(500).json({ error: 'Error fetching dealerships by state' });
}
});

// Express route to fetch dealer by a particular id
app.get('/fetchDealer/:id', async (req, res) => {
//Write your code here
try {
const document = await Dealerships.findOne({id: req.params.id});
if (!document) {
return res.status(404).json({ error: 'Dealer not found' });
}
res.json(document);
} catch (error) {
res.status(500).json({ error: 'Error fetching dealer by ID' });
}
});

//Express route to insert review
Expand Down Expand Up @@ -101,4 +122,4 @@ app.post('/insert_review', express.raw({ type: '*/*' }), async (req, res) => {
// Start the Express server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
});
29 changes: 29 additions & 0 deletions server/deployment.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
run: dealership
name: dealership
spec:
replicas: 1
selector:
matchLabels:
run: dealership
strategy:
rollingUpdate:
maxSurge: 25%
maxUnavailable: 25%
type: RollingUpdate
template:
metadata:
labels:
run: dealership
spec:
containers:
- image: us.icr.io/sn-labs-rajarshirayi/dealership:latest
imagePullPolicy: Always
name: dealership
ports:
- containerPort: 8000
protocol: TCP
restartPolicy: Always
4 changes: 2 additions & 2 deletions server/djangoapp/.env
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
backend_url =your backend url
sentiment_analyzer_url=your code engine deployment url
backend_url =https://rajarshirayi-3030.theiadockernext-0-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai
sentiment_analyzer_url=https://sentianalyzer.1zbei3afjojs.us-south.codeengine.appdomain.cloud
9 changes: 6 additions & 3 deletions server/djangoapp/admin.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
# from django.contrib import admin
# from .models import related models


# Register your models here.

Expand All @@ -11,3 +8,9 @@
# CarMakeAdmin class with CarModelInline

# Register models here
from django.contrib import admin
from .models import CarMake, CarModel

# Registering models with their respective admins
admin.site.register(CarMake)
admin.site.register(CarModel)
50 changes: 31 additions & 19 deletions server/djangoapp/models.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,37 @@
# Uncomment the following imports before adding the Model code
# Uncomment the following imports before adding the Model codee

# from django.db import models
# from django.utils.timezone import now
# from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator


# Create your models here.
class CarMake(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()

# <HINT> Create a Car Make model `class CarMake(models.Model)`:
# - Name
# - Description
# - Any other fields you would like to include in car make model
# - __str__ method to print a car make object
def __str__(self):
return self.name

class CarModel(models.Model):
car_make = models.ForeignKey(CarMake, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
CAR_TYPES = [
('SEDAN', 'Sedan'),
('SUV', 'SUV'),
('WAGON', 'Wagon'),
('HATCHBACK', 'Hatchback'),
('COUPE', 'Coupe'),
('MINIVAN', 'Minivan'),
('CONVERTIBLE', 'Convertible'),
('PICKUP', 'Pickup'),
]
type = models.CharField(max_length=20, choices=CAR_TYPES, default='SUV')
year = models.IntegerField(
default=2023,
validators=[
MaxValueValidator(2025),
MinValueValidator(2015),
]
)

# <HINT> Create a Car Model model `class CarModel(models.Model):`:
# - Many-To-One relationship to Car Make model (One Car Make has many
# Car Models, using ForeignKey field)
# - Name
# - Type (CharField with a choices argument to provide limited choices
# such as Sedan, SUV, WAGON, etc.)
# - Year (IntegerField) with min value 2015 and max value 2023
# - Any other fields you would like to include in car model
# - __str__ method to print a car make object
def __str__(self):
return self.name
92 changes: 91 additions & 1 deletion server/djangoapp/populate.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,92 @@
#comment
from .models import CarMake, CarModel


def initiate():
print("Populate not implemented. Add data manually")
car_make_data = [
{"name": "Nissan", "description": "Great cars. Japanese technology"},
{"name": "Mercedes", "description": "Great cars. German technology"},
{"name": "Audi", "description": "Great cars. German technology"},
{"name": "Kia", "description": "Great cars. Korean technology"},
{"name": "Toyota", "description": "Great cars. Japanese technology"},
]

car_make_instances = []
for data in car_make_data:
car_make_instances.append(
CarMake.objects.create(
name=data['name'],
description=data['description']
)
)

# Create CarModel instances with the corresponding CarMake instances
car_model_data = [
{
"name": "Pathfinder", "type": "SUV", "year": 2023,
"car_make": car_make_instances[0]
},
{
"name": "Qashqai", "type": "SUV", "year": 2023,
"car_make": car_make_instances[0]
},
{
"name": "XTRAIL", "type": "SUV", "year": 2023,
"car_make": car_make_instances[0]
},
{
"name": "A-Class", "type": "SUV", "year": 2023,
"car_make": car_make_instances[1]
},
{
"name": "C-Class", "type": "SUV", "year": 2023,
"car_make": car_make_instances[1]
},
{
"name": "E-Class", "type": "SUV", "year": 2023,
"car_make": car_make_instances[1]
},
{
"name": "A4", "type": "SUV", "year": 2023,
"car_make": car_make_instances[2]
},
{
"name": "A5", "type": "SUV", "year": 2023,
"car_make": car_make_instances[2]
},
{
"name": "A6", "type": "SUV", "year": 2023,
"car_make": car_make_instances[2]
},
{
"name": "Sorrento", "type": "SUV", "year": 2023,
"car_make": car_make_instances[3]
},
{
"name": "Carnival", "type": "SUV", "year": 2023,
"car_make": car_make_instances[3]},
{
"name": "Cerato", "type": "Sedan", "year": 2023,
"car_make": car_make_instances[3]
},
{
"name": "Corolla", "type": "Sedan", "year": 2023,
"car_make": car_make_instances[4]
},
{
"name": "Camry", "type": "Sedan", "year": 2023,
"car_make": car_make_instances[4]
},
{
"name": "Kluger", "type": "SUV", "year": 2023,
"car_make": car_make_instances[4]
},
]

for data in car_model_data:
CarModel.objects.create(
name=data['name'],
car_make=data['car_make'],
type=data['type'],
year=data['year']
)
45 changes: 36 additions & 9 deletions server/djangoapp/restapis.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
# Uncomment the imports below before you add the function code
# import requests
import requests
import os
from dotenv import load_dotenv

Expand All @@ -11,12 +10,40 @@
'sentiment_analyzer_url',
default="http://localhost:5050/")

# def get_request(endpoint, **kwargs):
# Add code for get requests to back end

# def analyze_review_sentiments(text):
# request_url = sentiment_analyzer_url+"analyze/"+text
# Add code for retrieving sentiments
def get_request(endpoint, **kwargs):
params = ""
if (kwargs):
for key, value in kwargs.items():
params = params+key+"="+value+"&"
request_url = backend_url+endpoint+"?"+params
print("GET from {} ".format(request_url))
try:
# Call get method of requests library with URL and parameters
response = requests.get(request_url)
return response.json()
except Exception:
# If any error occurs
print("Network exception occurred")

# def post_review(data_dict):
# Add code for posting review

def analyze_review_sentiments(text):
request_url = sentiment_analyzer_url+"analyze/"+text
try:
# Call get method of requests library with URL and parameters
response = requests.get(request_url)
return response.json()
except Exception as err:
print(f"Unexpected {err=}, {type(err)=}")
print("Network exception occurred")


def post_review(data_dict):
request_url = backend_url + "/insert_review"
try:
response = requests.post(request_url, json=data_dict)
print(response.json())
return response.json()
except Exception as e:
print(f"Network exception occurred: {e}")
return {"status": 500, "message": "Internal Server Error"}
Loading