Skip to content

Commit d502689

Browse files
Remove Sqlalchemy Serializer (#281)
2 parents 9dcbe67 + be928ae commit d502689

File tree

7 files changed

+84
-291
lines changed

7 files changed

+84
-291
lines changed

labconnect/helpers.py

Lines changed: 9 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import orjson
44
from flask.json.provider import JSONProvider
5-
from sqlalchemy_serializer import SerializerMixin
65

76

87
class SemesterEnum(EnumPython):
@@ -59,30 +58,6 @@ def loads(s, **kwargs):
5958
return orjson.loads(s)
6059

6160

62-
class LeadsCustomSerializerMixin(SerializerMixin):
63-
# date_format = "%s" # Unixtimestamp (seconds)
64-
# datetime_format = "%Y %b %d %H:%M:%S.%f"
65-
# time_format = "%H:%M.%f"
66-
professor = "lab_manager.name"
67-
pass
68-
69-
70-
class CustomSerializerMixin(SerializerMixin):
71-
# date_format = "%s" # Unixtimestamp (seconds)
72-
# datetime_format = "%Y %b %d %H:%M:%S.%f"
73-
# time_format = "%H:%M.%f"
74-
decimal_format = "{:0>10.3}"
75-
76-
77-
# pass in a tuple of opportunity, lead, labmanager
78-
def serializeOpportunity(data):
79-
oppData = data[0].to_dict()
80-
oppData["professor"] = data[2].name
81-
oppData["department"] = data[2].department_id
82-
83-
return oppData
84-
85-
8661
def prepare_flask_request(request):
8762
# If server is behind proxys or balancers use the HTTP_X_FORWARDED fields
8863
url_data = request.host_url + request.script_root
@@ -124,3 +99,12 @@ def format_credits(credit_1, credit_2, credit_3, credit_4):
12499
return "1-4 Credits"
125100
else:
126101
return f"{','.join(credits_output)} Credits"
102+
103+
104+
def convert_to_enum(location_string) -> LocationEnum | None:
105+
try:
106+
return LocationEnum[
107+
location_string.upper()
108+
] # Use upper() for case-insensitivity
109+
except KeyError:
110+
return None # Or raise an exception if you prefer

labconnect/main/discover_routes.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
User,
1111
UserMajors,
1212
)
13+
from labconnect.serializers import serialize_opportunity
1314

1415
from . import main_blueprint
1516

@@ -64,5 +65,5 @@ def discover_data(jwt_identity, limit):
6465
.order_by(Opportunities.last_updated.desc())
6566
).scalars()
6667

67-
result = [opportunity.to_dict() for opportunity in data]
68+
result = [serialize_opportunity(opportunity) for opportunity in data]
6869
return result

labconnect/main/opportunity_routes.py

Lines changed: 30 additions & 174 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,12 @@
55
from sqlalchemy import func
66

77
from labconnect import db
8-
from labconnect.helpers import LocationEnum, SemesterEnum, format_credits
8+
from labconnect.helpers import (
9+
LocationEnum,
10+
SemesterEnum,
11+
format_credits,
12+
convert_to_enum,
13+
)
914
from labconnect.models import (
1015
LabManager,
1116
Leads,
@@ -17,6 +22,7 @@
1722
RecommendsMajors,
1823
UserSavedOpportunities,
1924
)
25+
from labconnect.serializers import serialize_opportunity
2026

2127
from . import main_blueprint
2228

@@ -67,45 +73,11 @@ def searchOpportunity(query: str):
6773

6874
data = db.session.execute(stmt).scalars().all()
6975

70-
results = []
71-
72-
for opportunity in data:
73-
results.append(opportunity.to_dict())
76+
results = [serialize_opportunity(opportunity) for opportunity in data]
7477

7578
return results
7679

7780

78-
# @main_blueprint.get("/opportunity")
79-
# def getOpportunity2():
80-
# if not request.data:
81-
# abort(400)
82-
# json_request_data = request.get_json()
83-
# if not json_request_data:
84-
# abort(400)
85-
# id = json_request_data.get("id", None)
86-
# if not id:
87-
# abort(400)
88-
# data = db.first_or_404(db.select(Opportunities).where(Opportunities.id == id))
89-
# result = data.to_dict()
90-
# return result
91-
92-
93-
def convert_to_enum(location_string):
94-
try:
95-
return LocationEnum[
96-
location_string.upper()
97-
] # Use upper() for case-insensitivity
98-
except KeyError:
99-
return None # Or raise an exception if you prefer
100-
101-
102-
def packageOpportunity(opportunityInfo, professorInfo):
103-
data = opportunityInfo.to_dict()
104-
data["professor"] = professorInfo.name
105-
data["department"] = professorInfo.department_id
106-
return data
107-
108-
10981
def packageIndividualOpportunity(opportunityInfo):
11082
data = {
11183
"id": opportunityInfo.id,
@@ -210,8 +182,7 @@ def getOpportunity(opp_id: int):
210182
Opportunities.id == RecommendsClassYears.opportunity_id,
211183
)
212184
.where(Opportunities.id == opp_id)
213-
.group_by(Opportunities.id)
214-
185+
.group_by(Opportunities.id)
215186
)
216187

217188
data = query.all()
@@ -238,7 +209,7 @@ def getOpportunities():
238209
.order_by(Opportunities.last_updated.desc())
239210
.distinct()
240211
).scalars()
241-
result = [opportunity.to_dict() for opportunity in data]
212+
result = [serialize_opportunity(opportunity) for opportunity in data]
242213
return result
243214

244215

@@ -362,103 +333,11 @@ def filterOpportunities():
362333
if not data:
363334
abort(404)
364335

365-
result = [opportunity.to_dict() for opportunity in data]
336+
result = [serialize_opportunity(opportunity) for opportunity in data]
366337

367338
return result
368339

369340

370-
# @main_blueprint.put("/opportunity")
371-
# def changeActiveStatus2():
372-
373-
# if not request.data:
374-
# abort(400)
375-
376-
# json_request_data = request.get_json()
377-
378-
# if not json_request_data:
379-
# abort(400)
380-
381-
# postID = json_request_data.get("id", None)
382-
# status = json_request_data.get("status", None)
383-
384-
# if (
385-
# postID is None
386-
# or status is None
387-
# or not isinstance(postID, int)
388-
# or not isinstance(status, bool)
389-
# ):
390-
# abort(400)
391-
392-
# opportunity = db.first_or_404(
393-
# db.select(Opportunities).where(Opportunities.id == postID)
394-
# )
395-
# opportunity.active = status
396-
# db.session.commit()
397-
# return {"msg": "Opportunity updated successfully"}, 200
398-
399-
400-
# @main_blueprint.get("/getOpportunityMeta/<int:id>")
401-
# def getOpportunityMeta(id: int):
402-
# query = db.session.execute(
403-
# db.select(
404-
# Opportunities, RecommendsMajors, RecommendsCourses, RecommendsClassYears
405-
# )
406-
# .where(Opportunities.id == id)
407-
# .join(RecommendsMajors, RecommendsMajors.opportunity_id == Opportunities.id)
408-
# .join(RecommendsCourses, RecommendsCourses.opportunity_id == Opportunities.id)
409-
# .join(
410-
# RecommendsClassYears,
411-
# RecommendsClassYears.opportunity_id == Opportunities.id,
412-
# )
413-
# )
414-
# data = query.all()
415-
# print(data)
416-
417-
418-
# if not data or len(data) == 0:
419-
# abort(404)
420-
421-
# dictionary = data[0][0].to_dict()
422-
# dictionary["semester"] = dictionary["semester"].upper()
423-
# dictionary["courses"] = set()
424-
# dictionary["majors"] = set()
425-
# dictionary["years"] = set()
426-
427-
# for row in data:
428-
# dictionary["courses"].add(row[2].course_code)
429-
# dictionary["majors"].add(row[1].major_code)
430-
# dictionary["years"].add(row[3].class_year)
431-
432-
# dictionary["courses"] = list(dictionary["courses"])
433-
# dictionary["majors"] = list(dictionary["majors"])
434-
# dictionary["years"] = list(dictionary["years"])
435-
436-
# for i in range(len(dictionary["years"])):
437-
# dictionary["years"][i] = str(dictionary["years"][i])
438-
439-
# dictionary["credits"] = []
440-
# if dictionary["one_credit"]:
441-
# dictionary["credits"].append("1")
442-
443-
# if dictionary["two_credits"]:
444-
# dictionary["credits"].append("2")
445-
446-
# if dictionary["three_credits"]:
447-
# dictionary["credits"].append("3")
448-
449-
# if dictionary["four_credits"]:
450-
# dictionary["credits"].append("4")
451-
452-
# dictionary.pop("one_credit")
453-
# dictionary.pop("two_credits")
454-
# dictionary.pop("three_credits")
455-
# dictionary.pop("four_credits")
456-
457-
# return {"data": dictionary}
458-
459-
# abort(500)
460-
461-
462341
# Jobs page
463342
@main_blueprint.get("/getOpportunityCards")
464343
def getOpportunityCards():
@@ -472,28 +351,6 @@ def getOpportunityCards():
472351
return cards
473352

474353

475-
# @main_blueprint.get("/getOpportunities")
476-
# def getOpportunities():
477-
# # # query database for opportunity
478-
# query = db.session.execute(
479-
# db.select(Opportunities, Leads, LabManager)
480-
# .join(Leads, Leads.opportunity_id == Opportunities.id)
481-
# .join(LabManager, Leads.lab_manager_id == LabManager.id)
482-
# )
483-
# data = query.all()
484-
# print(data[0])
485-
486-
# # return data in the below format if opportunity is found
487-
# return {
488-
# "data": [
489-
# packageOpportunity(opportunity[0], opportunity[2])
490-
# for opportunity in data
491-
# ]
492-
# }
493-
494-
# abort(500)
495-
496-
497354
@main_blueprint.get("/staff/opportunities/<string:rcs_id>")
498355
def getLabManagerOpportunityCards(rcs_id: str) -> list[dict[str, str]]:
499356
query = (
@@ -756,8 +613,8 @@ def editOpportunity_get(opportunity_id):
756613
if credit
757614
]
758615

759-
years = [str(year.class_year) for year in years_data]
760-
#if years_data else []
616+
years = [str(year.class_year) for year in years_data]
617+
# if years_data else []
761618

762619
# Format opportunity data as JSON
763620
opportunity_data = {
@@ -896,22 +753,19 @@ def editOpportunity(opportunity_id):
896753
# )
897754
# db.session.add(new_lead)
898755

899-
900756
# Atttempt to fix by replacing data with request_data
901757
# Add the updated list of managers
902758
if "lab_manager_ids" in request_data:
903759
for lab_manager_id in request_data["lab_manager_ids"]:
904-
new_lead = Leads(
905-
lab_manager_id=lab_manager_id, opportunity_id=opportunity_id
906-
)
760+
new_lead = Leads()
761+
new_lead.lab_manager_id = lab_manager_id
762+
new_lead.opportunity_id = opportunity_id
907763
db.session.add(new_lead)
908764

909765
db.session.commit() # Commit all changes
910766

911-
912767
# db.session.commit() # Commit all changes
913768

914-
915769
return {"data": "Opportunity Updated"}, 200
916770

917771

@@ -949,10 +803,12 @@ def deleteOpportunity(opportunity_id):
949803

950804
return {"data": "Opportunity Deleted"}
951805

952-
#////////////////////////////////////////////////
806+
807+
# ////////////////////////////////////////////////
953808
# Store opportunities saved by a user
954809
# ***Specificaly storing a individual users saved opportunities***
955810

811+
956812
# Save User Opportunity
957813
@main_blueprint.post("/saveUserOpportunity/<int:opportunity_id>")
958814
@jwt_required()
@@ -964,30 +820,30 @@ def saveUserOpportunity(opportunity_id):
964820
save_opp_opportunity_id = db.session.get(Opportunities, opportunity_id)
965821
if not save_opp_opportunity_id:
966822
return {"error": "Opportunity not found"}, 404
967-
823+
968824
save_opp_user_id = get_jwt_identity()
969825

970826
# Check if the opportunity already exists in saved opportunities
971827
find_opp = db.session.execute(
972828
db.select(UserSavedOpportunities).where(
973-
(UserSavedOpportunities.user_id == save_opp_user_id) &
974-
(UserSavedOpportunities.opportunity_id == save_opp_opportunity_id)
829+
(UserSavedOpportunities.user_id == save_opp_user_id)
830+
& (UserSavedOpportunities.opportunity_id == save_opp_opportunity_id)
975831
)
976832
).scalar_one_or_none()
977833

978834
if find_opp:
979835
return {"message": "Opportunity already saved"}, 200
980836

981837
# Save the new opportunity
982-
new_opp = UserSavedOpportunities(
983-
user_id = save_opp_user_id,
984-
opportunity_id = save_opp_opportunity_id
985-
)
838+
new_opp = UserSavedOpportunities()
839+
new_opp.user_id = save_opp_user_id
840+
new_opp.opportunity_id = save_opp_opportunity_id
986841
db.session.add(new_opp)
987842
db.session.commit()
988843

989844
return {"message": "Opportunity saved successfully"}, 201
990845

846+
991847
# Delete an opportunitiy saved by a user
992848
@main_blueprint.delete("/deleteUserOpportunity/<int:opportunity_id>")
993849
@jwt_required()
@@ -1004,16 +860,16 @@ def deleteUserOpportunity(opportunity_id):
1004860
# Find the saved opportunity
1005861
get_saved_opp_info = db.session.execute(
1006862
db.select(UserSavedOpportunities).where(
1007-
(UserSavedOpportunities.user_id == save_opp_user_id) &
1008-
(UserSavedOpportunities.opportunity_id == save_opp_opportunity_id)
863+
(UserSavedOpportunities.user_id == save_opp_user_id)
864+
& (UserSavedOpportunities.opportunity_id == save_opp_opportunity_id)
1009865
)
1010866
).scalar_one_or_none()
1011867

1012868
if not get_saved_opp_info:
1013869
return {"message": "Opportunity not found"}, 404
1014870

1015-
# Delete the opportunity
871+
# Delete the opportunity
1016872
db.session.delete(get_saved_opp_info)
1017873
db.session.commit()
1018874

1019-
return {"message": "Opportunity deleted"}, 200
875+
return {"message": "Opportunity deleted"}, 200

0 commit comments

Comments
 (0)