Skip to content

Commit

Permalink
upd
Browse files Browse the repository at this point in the history
  • Loading branch information
Chacoon3 committed Nov 28, 2023
1 parent aea1770 commit e611c74
Show file tree
Hide file tree
Showing 11 changed files with 129 additions and 22 deletions.
3 changes: 2 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,6 @@ EXPOSE 8000
# CMD python manage.py makemigrations && python manage.py migrate && gunicorn -b 0.0.0.0:8000 sim_server_django.wsgi:application
CMD python manage.py makemigrations bmgt435_elp && \
python manage.py migrate && \
daphne -b 0.0.0.0 -p 8000 sim_server_django.asgi:application
# daphne -b 0.0.0.0 -p 8000 sim_server_django.asgi:application
gunicorn -b 0.0.0.0:8000 sim_server_django.wsgi:application -w 4
# CMD python manage.py makemigrations && python manage.py migrate && python manage.py runserver
6 changes: 3 additions & 3 deletions bmgt435_elp/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class BMGTUserAdmin(admin.ModelAdmin):

class CaseAdmin(admin.ModelAdmin):
fieldsets = [
("None", {"fields": ["name", "max_submission",]}),
("None", {"fields": ["id", "name", "max_submission",]}),
]

list_display = ["id", "name", "create_time", "max_submission", "visible",]
Expand All @@ -29,10 +29,10 @@ class CaseRecordAdmin(admin.ModelAdmin):

class CaseConfigAdmin(admin.ModelAdmin):
fieldsets = [
("None", {"fields": ["case_id", "semester_id", "create_time", "edited_time", "config_json",]}),
("None", {"fields": ["case_id", "create_time", "edited_time", "config_json",]}),
]

list_display = ["id", "case_id", "semester_id", "create_time", "edited_time", "config_json",]
list_display = ["id", "case_id", "create_time", "edited_time", "config_json",]


class GroupAdmin(admin.ModelAdmin):
Expand Down
18 changes: 10 additions & 8 deletions bmgt435_elp/apis.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from .simulation import FoodDelivery, SimulationException
from .bmgtModels import *
from .utils.apiUtils import request_error_handler, password_valid, generic_paginated_query, pager_params_from_request, create_pager_params, AppResponse
from .utils.databaseUtils import InMemoryCache

import pandas as pd
import json
Expand Down Expand Up @@ -37,9 +36,14 @@ def _get_session_user(request: HttpRequest) -> BMGTUser:

class AuthApi:

MAX_AGE_REMEMBER = 60 * 60 * 24 * 7 # 7 days

@staticmethod
def __set_auth_cookie(response: HttpResponse, user: BMGTUser) -> None:
response.set_cookie('id', str(user.id), samesite='strict', secure=True, httponly=True)
def __set_auth_cookie(response: HttpResponse, user: BMGTUser, remember: bool) -> None:
if remember:
response.set_cookie('id', str(user.id), samesite='strict', secure=True, httponly=True, max_age=AuthApi.MAX_AGE_REMEMBER)
else:
response.set_cookie('id', str(user.id), samesite='strict', secure=True, httponly=True)

@staticmethod
def __clear_auth_cookie(response: HttpResponse) -> None:
Expand All @@ -54,9 +58,10 @@ def sign_in(request: HttpRequest) -> AppResponse:
data = json.loads(request.body)
did = data['did']
password = data['password']
remember = data['remember']
user = BMGTUser.objects.get(did=did, activated=True,)
if check_password(password, user.password):
AuthApi.__set_auth_cookie(resp, user)
AuthApi.__set_auth_cookie(resp, user, remember)
resp.resolve(user)
else:
resp.reject("Sign in failed. Please check your directory ID and password!")
Expand Down Expand Up @@ -289,7 +294,7 @@ def submit(request: HttpRequest) -> HttpResponse:
# id to simulation case mapping
match case_id:
case 1: # food center
params = data.get('case_params')
params = data['case_params']
configQuery = BMGTCaseConfig.objects.filter(case_id=case_id,)
if configQuery.exists():
config = json.loads(configQuery.get().config_json)
Expand Down Expand Up @@ -460,7 +465,6 @@ def update_food_delivery_config(request: HttpRequest) -> HttpResponse:
try:
resp = AppResponse()
data = json.loads(request.body)
semester_id = data['semester_id']
case_id = FOOD_DELIVERY_CASE_ID
query = BMGTCaseConfig.objects.filter(case_id=case_id, )
if query.exists():
Expand Down Expand Up @@ -495,8 +499,6 @@ def view_food_delivery_config(request: HttpRequest) -> HttpResponse:
pager_params['case_id'] = FOOD_DELIVERY_CASE_ID
return generic_paginated_query(BMGTCaseConfig, pager_params)



@request_error_handler
@require_GET
@staticmethod
Expand Down
5 changes: 1 addition & 4 deletions bmgt435_elp/bmgtModels.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,11 +163,10 @@ class BMGTCaseConfig(BMGTModelBase):
class Meta:
app_label = APP_LABEL
constraints = [
models.UniqueConstraint(fields=('case_id', 'semester_id'), name='unique_case_config'),
models.UniqueConstraint(fields=('case_id',), name='unique_case_config'),
]

case = models.ForeignKey(BMGTCase, on_delete=models.CASCADE, null=False)
semester = models.ForeignKey(BMGTSemester, on_delete=models.CASCADE, null=False)
config_json = BMGTJsonField(null=False, default="", unique=False) # editable configuration regarding a case
edited_time = models.DateTimeField(auto_created=True, default=timezone.now, null=False)

Expand All @@ -178,8 +177,6 @@ def as_dictionary(self) -> dict:
edited_time=timezone.make_naive(self.edited_time).isoformat(sep=' ', timespec='seconds'),
case_id=self.case.id if self.case else None,
case_name=self.case.name if self.case else None,
semester_id=self.semester.id if self.semester else None,
semester_name=self.semester.name if self.semester else None,
config_json=self.config_json,
)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Generated by Django 4.2.1 on 2023-11-28 20:45

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('bmgt435_elp', '0003_bmgtsystemstatus_bmgtgroup_is_frozen_and_more'),
]

operations = [
migrations.RemoveConstraint(
model_name='bmgtcaseconfig',
name='unique_case_config',
),
migrations.RemoveField(
model_name='bmgtcaseconfig',
name='semester',
),
migrations.AddConstraint(
model_name='bmgtcaseconfig',
constraint=models.UniqueConstraint(fields=('case_id',), name='unique_case_config'),
),
]
4 changes: 2 additions & 2 deletions bmgt435_elp/simulation/FoodDelivery.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,13 +358,13 @@ def run(self):
]
for centerwise_df, c_name in zip(arr_df_per_center_statistics, history.keys()):
# add center name and week index columns
centerwise_df['center'] = c_name
centerwise_df['hub'] = c_name
centerwise_df['week'] = range(1, FoodDelivery.__num_weeks + 1)

df_per_center_statistics = pd.concat(arr_df_per_center_statistics, axis=0)

if self.__config is not None:
df_per_center_statistics['center'] = df_per_center_statistics['center'].map(
df_per_center_statistics['hub'] = df_per_center_statistics['hub'].map(
{v: k for k, v in self.__config.items()}
)

Expand Down
82 changes: 79 additions & 3 deletions bmgt435_elp/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ def _signUp(did:str, password:str):
return resp


def _signIn(did:str, password:str):
def _signIn(did:str, password:str, remember:bool = False):
req = RequestFactory().post(
'/bmgt435-service/api/auth/sign-in',
json.dumps({'did':did, 'password':password}),
json.dumps({'did':did, 'password':password, 'remember':remember}),
'application/json'
)
resp = AuthApi.sign_in(req)
Expand Down Expand Up @@ -492,4 +492,80 @@ def testCreateSemesterNegative(self):
c.cookies = SimpleCookie(negCookies)
resp = c.post('/bmgt435-service/api/manage/semester/create', json.dumps({'year':2021, 'season':'fall'}), content_type='application/json')
self.assertRejected(resp)
self.assertEqual(BMGTSemester.objects.count(), 1)
self.assertEqual(BMGTSemester.objects.count(), 1)


def testFoodDeliveryConfigPositive(self):
config= {
'config_json':[
[1, 2],
[2, 1],
[3, 4],
[4, 3],
[5, 6],
[6, 5],
]
}
c = Client()
c.cookies = SimpleCookie({'id':1})
resp = c.post('api/manage/food-delivery-config/update', json.dumps(config), content_type='application/json')
self.assertResolved(resp)


def testFoodDeliveryConfigNegative(self):
config= {
'config_json':[
[1, 2],
[2, 1],
[3, 4],
[4, 3],
[5, 6],
[6, 5],
]
}
c = Client()
c.cookies = SimpleCookie({'id':2})
resp = c.post('api/manage/food-delivery-config/update', json.dumps(config), content_type='application/json')
self.assertRejected(resp)

c.cookies = SimpleCookie({'id':-1})
resp = c.post('api/manage/food-delivery-config/update', json.dumps(config), content_type='application/json')
self.assertRejected(resp)

badConfig = {
'config_json':[
[1, 2],
[2, 1],
[3, 4],
[4, 3],
[5, 6],
[6, 5],
[7, 8],
]
}

c.cookies = SimpleCookie({'id':1})
resp = c.post('api/manage/food-delivery-config/update', json.dumps(badConfig), content_type='application/json')
self.assertRejected(resp)

badConfig2 = {
'config_json':[
[1, 2],
[2, 1],
[3, 4],
[4, 3],
[5, 6],
[6, 1],
]
}
resp = c.post('api/manage/food-delivery-config/update', json.dumps(badConfig2), content_type='application/json')
self.assertRejected(resp)


def testCaseConfigIntegrity(self):
try:
BMGTCaseConfig(case_id=1).save()
BMGTCaseConfig(case_id=1).save()
self.fail()
except IntegrityError:
return
6 changes: 5 additions & 1 deletion bmgt435_elp/utils/apiUtils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned, ValidationError
from django.db import IntegrityError
from django.db import IntegrityError, OperationalError
from django.core.paginator import Paginator, EmptyPage
from django.http import HttpRequest, HttpResponse
from http import HTTPStatus
Expand Down Expand Up @@ -62,6 +62,10 @@ def wrapped(request, *args, **kwargs) -> HttpResponse:
except ValueError as e:
resp = AppResponse()
resp.reject(e.args[0])

except OperationalError as e:
resp = AppResponse()
resp.reject(e.args[0])

except Exception as e:
# resp = HttpResponse()
Expand Down
Binary file modified db.sqlite3
Binary file not shown.
Binary file modified sim_server_django/__pycache__/settings.cpython-310.pyc
Binary file not shown.
2 changes: 2 additions & 0 deletions sim_server_django/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,13 +87,15 @@
},
},
}
print('Using MySQL database')
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
print('Using SQLite database')


# Password validation
Expand Down

0 comments on commit e611c74

Please sign in to comment.