Skip to content
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

Django proxy #89

Open
wants to merge 9 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
21 changes: 19 additions & 2 deletions server/database/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ mongoose.connect("mongodb://mongo_db:27017/",{'dbName':'dealershipsDB'});
const Reviews = require('./review');

const Dealerships = require('./dealership');
const dealership = require('./dealership');

try {
Reviews.deleteMany({}).then(()=>{
Expand Down Expand Up @@ -59,16 +60,32 @@ 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
backend_url =http://localhost:3030/
sentiment_analyzer_url=your code engine deployment url
6 changes: 6 additions & 0 deletions server/djangoapp/admin.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
# from django.contrib import admin
# from .models import related models

from django.contrib import admin
from .models import CarMake, CarModel
# Registering models with their respective admins


# Register your models here.
admin.site.register(CarMake)
admin.site.register(CarModel)

# CarModelInline class

Expand Down
33 changes: 30 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 @@ -13,6 +13,13 @@
# - 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,23 @@
# - 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: 37 additions & 1 deletion server/djangoapp/populate.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,38 @@
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]},
# 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'])
20 changes: 19 additions & 1 deletion server/djangoapp/restapis.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Uncomment the imports below before you add the function code
# import requests
import requests
import os
from dotenv import load_dotenv

Expand All @@ -13,6 +13,24 @@

# def get_request(endpoint, **kwargs):
# Add code for get requests to back end
def get_request(endpoint, **kwargs):
params = ""
if kwargs:
# Correctly format parameters
params = "&".join([f"{key}={value}" for key, value in kwargs.items()])

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)
response.raise_for_status() # Check for HTTP request errors
return response.json()
except requests.exceptions.RequestException as e:
# If any error occurs, print the error
print(f"Network exception occurred: {e}")
return None

# def analyze_review_sentiments(text):
# request_url = sentiment_analyzer_url+"analyze/"+text
Expand Down
9 changes: 9 additions & 0 deletions server/djangoapp/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Import the function to be tested
from restapis import get_request # Replace `your_module_name` with the actual module name

# Test the get_request function
response = get_request("/api/example", param1="value1", param2="value2")
if response:
print(response)
else:
print("Failed to get a valid response.")
14 changes: 10 additions & 4 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 django.contrib.auth import views as auth_views
from django.http import HttpResponse
from . import views

app_name = 'djangoapp'

urlpatterns = [
# # path for registration

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

path(route='login', view=views.login_user, name='login'),
path('logout/', views.logout_request, name='logout'),
path('register/', views.registration, name='register'),
path('get_cars/', views.get_cars, name='get_cars'),

# path for dealer reviews view

# path for add a review view
Expand Down
69 changes: 57 additions & 12 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 .models import CarMake, CarModel
from .populate import initiate


# Get an instance of a logger
Expand All @@ -39,13 +41,43 @@ def login_user(request):
return JsonResponse(data)

# Create a `logout_request` view to handle sign out request
# def logout_request(request):
# ...
@csrf_exempt
def logout_request(request):
if request.method == 'POST':
logout(request)
return JsonResponse({'status': 'success'})
return JsonResponse({'status': 'fail', 'message': 'Invalid request method'}, status=400)

# Create a `registration` view to handle sign up request
# @csrf_exempt
# def registration(request):
# ...
@csrf_exempt
def registration(request):
context = {}
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
# a list of dealerships
Expand All @@ -63,3 +95,16 @@ def login_user(request):
# Create a `add_review` view to submit a review
# def add_review(request):
# ...


@csrf_exempt
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})
25 changes: 21 additions & 4 deletions server/djangoproj/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
from pathlib import Path


APPEND_SLASH = True

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

Expand All @@ -28,8 +30,8 @@
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []
CSRF_TRUSTED_ORIGINS = []
ALLOWED_HOSTS=['localhost','127.0.0.1']
CSRF_TRUSTED_ORIGINS=[]

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [],
Expand All @@ -51,6 +53,7 @@
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
Expand All @@ -61,7 +64,11 @@
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'DIRS': [
os.path.join(BASE_DIR, 'frontend/static'),
os.path.join(BASE_DIR, 'frontend/build'),
os.path.join(BASE_DIR, 'frontend/build/static'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
Expand Down Expand Up @@ -134,5 +141,15 @@

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

STATICFILES_DIRS = []
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'frontend/static'),
os.path.join(BASE_DIR, 'frontend/build'),
os.path.join(BASE_DIR, 'frontend/build/static'),
]

LOGOUT_REDIRECT_URL = '/'

SESSION_COOKIE_NAME = 'sessionid'
SESSION_EXPIRE_AT_BROWSER_CLOSE = True


4 changes: 4 additions & 0 deletions server/djangoproj/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,8 @@
path('admin/', admin.site.urls),
path('djangoapp/', include('djangoapp.urls')),
path('', TemplateView.as_view(template_name="Home.html")),
path('about/', TemplateView.as_view(template_name="About.html")),
path('contact/', TemplateView.as_view(template_name="Contact.html")),
path('login/', TemplateView.as_view(template_name="index.html")),
path('register/', TemplateView.as_view(template_name="index.html")),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Loading