Skip to content

Commit

Permalink
Merge pull request #1378 from gtech-mulearn:dev
Browse files Browse the repository at this point in the history
[MAJOR] Created a system to handle all unhandled exceptions
  • Loading branch information
MZaFaRM authored Oct 19, 2023
2 parents b2bbfd8 + 24ba118 commit c2a5aef
Show file tree
Hide file tree
Showing 13 changed files with 198 additions and 211 deletions.
23 changes: 8 additions & 15 deletions api/dashboard/campus/campus_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,21 +212,14 @@ class WeeklyKarmaAPI(APIView):

@role_required([RoleType.CAMPUS_LEAD.value, RoleType.ENABLER.value])
def get(self, request):
try:
user_id = JWTUtils.fetch_user_id(request)

user_org_link = get_user_college_link(user_id)
user_id = JWTUtils.fetch_user_id(request)

if user_org_link.org is None:
return CustomResponse(
general_message="Campus lead has no college"
).get_failure_response()
user_org_link = get_user_college_link(user_id)

serializer = serializers.WeeklyKarmaSerializer(user_org_link)
return CustomResponse(response=serializer.data).get_success_response()
if user_org_link.org is None:
return CustomResponse(
general_message="Campus lead has no college"
).get_failure_response()

except Exception as e:
raise CustomException(
detail='somthing went wrong',
status_code=403
)
serializer = serializers.WeeklyKarmaSerializer(user_org_link)
return CustomResponse(response=serializer.data).get_success_response()
42 changes: 30 additions & 12 deletions api/dashboard/error_log/error_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,43 +14,61 @@
class DownloadErrorLogAPI(APIView):
authentication_classes = [CustomizePermission]

@role_required([RoleType.ADMIN.value, RoleType.FELLOW.value, RoleType.TECH_TEAM.value])
@role_required(
[RoleType.ADMIN.value, RoleType.FELLOW.value, RoleType.TECH_TEAM.value]
)
def get(self, request, log_name):
error_log = f"{log_path}/{log_name}.log"
if os.path.exists(error_log):
response = FileResponse(open(error_log, 'rb'), content_type='application/octet-stream')
response['Content-Disposition'] = f'attachment; filename="{log_name}"'
response = FileResponse(
open(error_log, "rb"), content_type="application/octet-stream"
)
response["Content-Disposition"] = f'attachment; filename="{log_name}"'
return response
return CustomResponse(general_message=f"{log_name} Not Found").get_failure_response()
return CustomResponse(
general_message=f"{log_name} Not Found"
).get_failure_response()


class ViewErrorLogAPI(APIView):
authentication_classes = [CustomizePermission]

@role_required([RoleType.ADMIN.value, RoleType.FELLOW.value, RoleType.TECH_TEAM.value])
@role_required(
[RoleType.ADMIN.value, RoleType.FELLOW.value, RoleType.TECH_TEAM.value]
)
def get(self, request, log_name):
error_log = f"{log_path}/{log_name}.log"
if os.path.exists(error_log):
try:
with open(error_log, 'r') as log_file:
with open(error_log, "r") as log_file:
log_content = log_file.read()
return CustomResponse(response=log_content).get_success_response()
except Exception as e:
return CustomResponse(general_message=f'Error reading log file').get_failure_response()
return CustomResponse(
general_message="Error reading log file"
).get_failure_response()

return CustomResponse(general_message=f"{log_name} Not Found").get_failure_response()
return CustomResponse(
general_message=f"{log_name} Not Found"
).get_failure_response()


class ClearErrorLogAPI(APIView):
def get(self, request, log_name):
error_log = f"{log_path}/{log_name}.log"
if os.path.exists(error_log):
try:
with open(error_log, 'w') as log_file:
with open(error_log, "w") as log_file:
log_file.truncate(0)
return CustomResponse(general_message=f'{log_name} log cleared successfully').get_success_response()
return CustomResponse(
general_message=f"{log_name} log cleared successfully"
).get_success_response()
except Exception as e:
print(e)
return CustomResponse(general_message=f'Error reading log file').get_failure_response()
return CustomResponse(
general_message="Error reading log file"
).get_failure_response()

return CustomResponse(general_message=f"{log_name} Not Found").get_failure_response()
return CustomResponse(
general_message=f"{log_name} Not Found"
).get_failure_response()
60 changes: 27 additions & 33 deletions api/dashboard/location/location_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,44 +15,38 @@ class CountryDataAPI(APIView):

@role_required([RoleType.ADMIN.value])
def get(self, request, country_id=None):
try:
if country_id:
countries = Country.objects.filter(id=country_id)
else:
countries = Country.objects.all()

paginated_queryset = CommonUtils.get_paginated_queryset(
countries, request, ["name"], {"name": "name"}
)

serializer = location_serializer.CountryRetrievalSerializer(
paginated_queryset.get("queryset"), many=True
)
return CustomResponse().paginated_response(
data=serializer.data, pagination=paginated_queryset.get("pagination")
)
except Exception as e:
return CustomResponse(general_message=str(e)).get_failure_response()
if country_id:
countries = Country.objects.filter(id=country_id)
else:
countries = Country.objects.all()

paginated_queryset = CommonUtils.get_paginated_queryset(
countries, request, ["name"], {"name": "name"}
)

serializer = location_serializer.CountryRetrievalSerializer(
paginated_queryset.get("queryset"), many=True
)
return CustomResponse().paginated_response(
data=serializer.data, pagination=paginated_queryset.get("pagination")
)

@role_required([RoleType.ADMIN.value])
def post(self, request):
try:
user_id = JWTUtils.fetch_user_id(request)
serializer = location_serializer.CountryCreateEditSerializer(
data=request.data, context={"user_id": user_id}
)

if serializer.is_valid():
serializer.save()
return CustomResponse(
general_message=serializer.data
).get_success_response()
user_id = JWTUtils.fetch_user_id(request)
serializer = location_serializer.CountryCreateEditSerializer(
data=request.data, context={"user_id": user_id}
)

if serializer.is_valid():
serializer.save()
return CustomResponse(
general_message=serializer.errors
).get_failure_response()
except Exception as e:
return CustomResponse(general_message=str(e)).get_failure_response()
general_message=serializer.data
).get_success_response()

return CustomResponse(
general_message=serializer.errors
).get_failure_response()

@role_required([RoleType.ADMIN.value])
def patch(self, request, country_id):
Expand Down
7 changes: 4 additions & 3 deletions api/dashboard/profile/profile_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from db.organization import UserOrganizationLink
from db.task import InterestGroup, KarmaActivityLog, Level, TaskList, Wallet, UserIgLink, UserLvlLink
from db.user import User, UserSettings, Socials
from utils.exception import CustomException
from utils.permission import JWTUtils
from utils.types import OrganizationType, RoleType, MainRoles
from utils.utils import DateTimeUtils
Expand Down Expand Up @@ -323,7 +324,7 @@ def update(self, instance, validated_data):
for ig_data in ig_details
]
if len(user_ig_links) > 3:
raise ValueError("Cannot add more than 3 interest groups")
raise CustomException("Cannot add more than 3 interest groups")
UserIgLink.objects.bulk_create(user_ig_links)
return super().update(instance, validated_data)

Expand Down Expand Up @@ -383,9 +384,9 @@ def create_karma_activity_log(task_title, karma_value):
old_account_url = old_accounts[account]
if account_url != old_account_url:
if old_account_url is None:
create_karma_activity_log("social_" + account, 50)
create_karma_activity_log(f"social_{account}", 50)
elif account_url is None:
create_karma_activity_log("social_" + account, -50)
create_karma_activity_log(f"social_{account}", -50)

instance.save()
return instance
59 changes: 21 additions & 38 deletions api/dashboard/profile/profile_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from db.task import InterestGroup, KarmaActivityLog, Level
from db.user import Role
from db.user import User, UserSettings, UserRoleLink, Socials
from utils.exception import CustomException
from utils.permission import CustomizePermission, JWTUtils
from utils.response import CustomResponse
from utils.types import WebHookActions, WebHookCategory
Expand All @@ -14,8 +15,6 @@
import logging




class UserProfileEditView(APIView):
authentication_classes = [CustomizePermission]

Expand Down Expand Up @@ -60,37 +59,23 @@ class UserIgEditView(APIView):
def get(self, request):
user_id = JWTUtils.fetch_user_id(request)

user_ig = InterestGroup.objects.filter(
user_ig_link_ig__user_id=user_id
).all()
user_ig = InterestGroup.objects.filter(user_ig_link_ig__user_id=user_id).all()

serializer = profile_serializer.UserIgListSerializer(
user_ig,
many=True
)
serializer = profile_serializer.UserIgListSerializer(user_ig, many=True)

return CustomResponse(
response=serializer.data
).get_success_response()
return CustomResponse(response=serializer.data).get_success_response()

def patch(self, request):

logger = logging.getLogger(__name__)

try:
user_id = JWTUtils.fetch_user_id(request)
user = User.objects.get(id=user_id)

serializer = profile_serializer.UserIgEditSerializer(
user,
data=request.data,
partial=True
user, data=request.data, partial=True
)

if not serializer.is_valid():
return CustomResponse(
response=serializer.errors
).get_failure_response()
return CustomResponse(response=serializer.errors).get_failure_response()

serializer.save()
DiscordWebhooks.general_updates(
Expand All @@ -102,16 +87,8 @@ def patch(self, request):
general_message="Interest Group edited successfully"
).get_success_response()

except ValueError as e:
return CustomResponse(
general_message=str(e)
).get_failure_response()

except Exception as e:
logger.exception("An error occurred: %s", str(e))
return CustomResponse(
general_message="Somthing went wrong"
).get_failure_response()
except CustomException as e:
return CustomResponse(general_message=str(e)).get_failure_response()


class UserProfileAPI(APIView):
Expand Down Expand Up @@ -140,9 +117,7 @@ def get(self, request, muid=None):
else:
JWTUtils.is_jwt_authenticated(request)

serializer = profile_serializer.UserProfileSerializer(
user, many=False
)
serializer = profile_serializer.UserProfileSerializer(user, many=False)

return CustomResponse(response=serializer.data).get_success_response()

Expand Down Expand Up @@ -259,10 +234,14 @@ def get(self, request, muid=None):
if muid is not None:
user = User.objects.filter(muid=muid).first()
if user is None:
return CustomResponse(general_message="Invalid muid").get_failure_response()
return CustomResponse(
general_message="Invalid muid"
).get_failure_response()
user_settings = UserSettings.objects.filter(user_id=user).first()
if not user_settings.is_public:
return CustomResponse(general_message="Private Profile").get_failure_response()
return CustomResponse(
general_message="Private Profile"
).get_failure_response()
user_id = user.id
else:
JWTUtils.is_jwt_authenticated(request)
Expand All @@ -279,8 +258,12 @@ class SocialsAPI(APIView):
def put(self, request):
user_id = JWTUtils.fetch_user_id(request)
social_instance = Socials.objects.filter(user_id=user_id).first()
serializer = LinkSocials(instance=social_instance, data=request.data, context={"request": request})
serializer = LinkSocials(
instance=social_instance, data=request.data, context={"request": request}
)
if serializer.is_valid():
serializer.save()
return CustomResponse(general_message="Socials Updated").get_success_response()
return CustomResponse(
general_message="Socials Updated"
).get_success_response()
return CustomResponse(response=serializer.errors).get_failure_response()
Loading

0 comments on commit c2a5aef

Please sign in to comment.