Skip to content

Config with ibm clud #202

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
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
Binary file added about_us.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added contact-us.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added dealer_details.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added dealer_review.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added dealerships.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added django_server.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added kansasDealers.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added login.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added logout.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added server/.DS_Store
Binary file not shown.
Binary file added server/admin_login.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
19 changes: 19 additions & 0 deletions server/database/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,16 +59,35 @@ app.get('/fetchReviews/dealer/:id', async (req, res) => {
// 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 documents' });
}
});

// 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 documents' });
}

});

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

//Express route to insert review
Expand Down
2 changes: 1 addition & 1 deletion 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
sentiment_analyzer_url= https://sentianalyzer.1x1iwekqmyi2.us-south.codeengine.appdomain.cloud
6 changes: 6 additions & 0 deletions server/djangoapp/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,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)
32 changes: 29 additions & 3 deletions server/djangoapp/models.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Uncomment the following imports before adding the Model code

# 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.utils.timezone import now
from django.core.validators import MaxValueValidator, MinValueValidator


# Create your models here.
Expand All @@ -12,7 +12,14 @@
# - Description
# - Any other fields you would like to include in car make model
# - __str__ method to print a car make object
class CarMake(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
# Other fields as needed

def __str__(self):
return self.name
# Return the name as the string representation

# <HINT> Create a Car Model model `class CarModel(models.Model):`:
# - Many-To-One relationship to Car Make model (One Car Make has many
Expand All @@ -23,3 +30,22 @@
# - 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
class CarModel(models.Model):
car_make = models.ForeignKey(CarMake, on_delete=models.CASCADE) # Many-to-One relationship
name = models.CharField(max_length=100)
CAR_TYPES = [
('SEDAN', 'Sedan'),
('SUV', 'SUV'),
('WAGON', 'Wagon'),
# Add more choices as required
]
type = models.CharField(max_length=10, choices=CAR_TYPES, default='SUV')
year = models.IntegerField(default=2023,
validators=[
MaxValueValidator(2023),
MinValueValidator(2015)
])
# Other fields as needed

def __str__(self):
return self.name # Return the name as the string representation
38 changes: 38 additions & 0 deletions server/djangoapp/populate.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,40 @@
def initiate():
print("Populate not implemented. Add data manually")
from .models import CarMake, CarModel

def initiate():
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]},
# Add more CarModel instances as needed
]

for data in car_model_data:
CarModel.objects.create(name=data['name'], car_make=data['car_make'], type=data['type'], year=data['year'])
18 changes: 17 additions & 1 deletion server/djangoapp/restapis.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,22 @@
# def analyze_review_sentiments(text):
# request_url = sentiment_analyzer_url+"analyze/"+text
# Add code for retrieving sentiments

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):
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:
print("Network exception occurred")
# Add code for posting review
20 changes: 13 additions & 7 deletions server/djangoapp/urls.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
# Uncomment the imports before you add the code
# from django.urls import path
from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
# from . import views
from . import views
from django.contrib.auth import views as auth_views


app_name = 'djangoapp'
urlpatterns = [
# # path for registration

# path for login
# path(route='login', view=views.login_user, name='login'),

path('register/', views.registration, name='Register'),
path(route='login', view=views.login_user, name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
path(route='get_cars', view=views.get_cars, name ='getcars'),
path(route='get_dealers', view=views.get_dealerships, name='get_dealers'),
path(route='get_dealers/<str:state>', view=views.get_dealerships, name='get_dealers_by_state'),
path(route='dealer/<int:dealer_id>', view=views.get_dealer_details, name='dealer_details'),
path(route='reviews/dealer/<int:dealer_id>', view=views.get_dealer_reviews, name='dealer_details'),
path(route='add_review', view=views.add_review, name='add_review'),
# path for dealer reviews view

# path for add a review view
Expand Down
133 changes: 107 additions & 26 deletions server/djangoapp/views.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
# Uncomment the required imports before adding the code

# from django.shortcuts import render
# from django.http import HttpResponseRedirect, HttpResponse
# from django.contrib.auth.models import User
# from django.shortcuts import get_object_or_404, render, redirect
# from django.contrib.auth import logout
# from django.contrib import messages
# from datetime import datetime
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404, render, redirect
from django.contrib.auth import logout
from django.contrib import messages
from datetime import datetime

from django.http import JsonResponse
from django.contrib.auth import login, authenticate
import logging
import json
from django.views.decorators.csrf import csrf_exempt
# from .populate import initiate
from .populate import initiate
from .models import CarMake, CarModel
from .restapis import get_request, analyze_review_sentiments, post_review


# Get an instance of a logger
Expand All @@ -25,41 +27,120 @@
# Create a `login_request` view to handle sign in request
@csrf_exempt
def login_user(request):
# Get username and password from request.POST dictionary
data = json.loads(request.body)
username = data['userName']
password = data['password']
# Try to check if provide credential can be authenticated
user = authenticate(username=username, password=password)
data = {"userName": username}
if user is not None:
# If user is valid, call login method to login current user
login(request, user)
data = {"userName": username, "status": "Authenticated"}
return JsonResponse(data)
if request.method == 'POST':
try:
data = json.loads(request.body)
username = data.get('userName')
password = data.get('password')

user = authenticate(username=username, password=password)

if user is not None:
login(request, user)
return JsonResponse({"userName": username, "status": "Authenticated"}, status=200)
else:
return JsonResponse({"error": "Invalid credentials"}, status=401)
except json.JSONDecodeError:
return JsonResponse({"error": "Invalid JSON"}, status=400)
else:
return JsonResponse({"error": "Only POST method allowed"}, status=405)

# Create a `logout_request` view to handle sign out request
# def logout_request(request):
# ...
def logout_request(request):
logout(request)
data = {"userName":""}
return JsonResponse(data)

# Create a `registration` view to handle sign up request
# @csrf_exempt
# def registration(request):
# ...
@csrf_exempt
def registration(request):
context = {}
# Load JSON data from the request body
data = json.loads(request.body)
username = data['userName']
password = data['password']
first_name = data['firstName']
last_name = data['lastName']
email = data['email']
username_exist = False
email_exist = False
try:
# Check if user already exists
User.objects.get(username=username)
username_exist = True
except:
# If not, simply log this is a new user
logger.debug("{} is new user".format(username))

# If it is a new user
if not username_exist:
# Create user in auth_user table
user = User.objects.create_user(username=username, first_name=first_name, last_name=last_name,password=password, email=email)
# Login the user and redirect to list page
login(request, user)
data = {"userName":username,"status":"Authenticated"}
return JsonResponse(data)
else :
data = {"userName":username,"error":"Already Registered"}
return JsonResponse(data)
# # Update the `get_dealerships` view to render the index page with
def get_dealerships(request, state="All"):
if(state == "All"):
endpoint = "/fetchDealers"
else:
endpoint = "/fetchDealers/"+state
dealerships = get_request(endpoint)
return JsonResponse({"status":200,"dealers":dealerships})
# a list of dealerships
# def get_dealerships(request):
# ...
def get_cars(request):
count = CarMake.objects.filter().count()
print(count)
if(count == 0):
initiate()
car_models = CarModel.objects.select_related('car_make')
cars = []
for car_model in car_models:
cars.append({"CarModel": car_model.name, "CarMake": car_model.car_make.name})
return JsonResponse({"CarModels":cars})

# Create a `get_dealer_reviews` view to render the reviews of a dealer
# def get_dealer_reviews(request,dealer_id):
# ...
def get_dealer_reviews(request, dealer_id):
# if dealer id has been provided
if(dealer_id):
endpoint = "/fetchReviews/dealer/"+str(dealer_id)
reviews = get_request(endpoint)
for review_detail in reviews:
response = analyze_review_sentiments(review_detail['review'])
print(response)
review_detail['sentiment'] = response['sentiment']
return JsonResponse({"status":200,"reviews":reviews})
else:
return JsonResponse({"status":400,"message":"Bad Request"})

# Create a `get_dealer_details` view to render the dealer details
# def get_dealer_details(request, dealer_id):
# ...

def get_dealer_details(request, dealer_id):
if(dealer_id):
endpoint = "/fetchDealer/"+str(dealer_id)
dealership = get_request(endpoint)
return JsonResponse({"status":200,"dealer":dealership})
else:
return JsonResponse({"status":400,"message":"Bad Request"})
# Create a `add_review` view to submit a review
# def add_review(request):
# ...
def add_review(request):
if(request.user.is_anonymous == False):
data = json.loads(request.body)
try:
response = post_review(data)
return JsonResponse({"status":200})
except:
return JsonResponse({"status":401,"message":"Error in posting review"})
else:
return JsonResponse({"status":403,"message":"Unauthorized"})
Loading