From eef1b17633787b5d9fa93c2fa9febaad40a321a4 Mon Sep 17 00:00:00 2001 From: nima Date: Thu, 6 May 2021 20:04:11 +0430 Subject: [PATCH 1/2] ad hoc refactor in utilities/responses.py --- utilities/responses.py | 188 ++++++++++++++++++++++------------------- 1 file changed, 99 insertions(+), 89 deletions(-) diff --git a/utilities/responses.py b/utilities/responses.py index 7c3f27d..2942b7f 100644 --- a/utilities/responses.py +++ b/utilities/responses.py @@ -2,44 +2,42 @@ main response handler, some of response handel throw middleware """ import time -import json -from django.http import HttpResponse from django.conf import settings from django.utils.translation import ugettext as _ +from rest_framework.response import Response class BaseResponse: + def __init__(self, **kwargs): + self.message = kwargs.get('message') + self.show_type = kwargs.get('show_type', settings.MESSAGE_SHOW_TYPE['TOAST']) + self.current_time = round(time.time()) + self.status = kwargs.get("status") + self.success = kwargs.get("success") + def send(self): status = self.__dict__.pop('status') - return HttpResponse( - json.dumps(self.__dict__), - status=status, - content_type="application/json" + return Response( + data=self.__dict__, + status=status ) class ErrorResponse(BaseResponse): - def __init__(self, message, dev_error=None, errors=None, show_type=settings.MESSAGE_SHOW_TYPE['TOAST'], status=400): - self.message = message + def __init__(self, dev_error=None, errors=None, **kwargs): + super().__init__(**kwargs) self.dev_error = dev_error self.errors = errors - self.show_type = show_type - self.current_time = round(time.time()) - self.success = False - self.status = status class SuccessResponse(BaseResponse): - def __init__(self, data=None, message=None, show_type=settings.MESSAGE_SHOW_TYPE['TOAST'], status=200, **kwargs): - self.data = data + def __init__(self, message, data=None, **kwargs): + super().__init__(**kwargs) self.message = message - self.show_type = show_type - self.current_time = round(time.time()) - self.success = True - self.index = kwargs['index'] if kwargs.get('index') is not None else None - self.total = kwargs['total'] if kwargs.get('total') is not None else None - self.status = status + self.data = data + self.index = kwargs.get('index') + self.total = kwargs.get('total') class ExceptionHandlerMiddleware(object): @@ -51,102 +49,114 @@ def __call__(self, request): return response + @staticmethod + def __make_response(status_code: int, extra: dict): + return { + 'success': True if status_code // 100 == 2 else False, + 'code': status_code, + 'current_time': round(time.time()), + 'show_type': settings.MESSAGE_SHOW_TYPE['NONE'], + **extra + } + @staticmethod def process_template_response(request, response): if response.status_code == 200 and hasattr(response, 'data') and isinstance(response.data, dict): # Ok - data = response.data - response.data = {'success': True, 'code': response.status_code, 'index': None, 'total': None, - 'current_time': round(time.time()), 'message': None, - 'show_type': settings.MESSAGE_SHOW_TYPE['NONE'], 'data': data} # response.data.update(data) + response.data = ExceptionHandlerMiddleware.__make_response(200, { + 'index': None, + 'total': None, + 'message': None, + 'data': response.data + }) elif response.status_code == 204: # No content it will never return data!!! because of 204 - data = response.data - response.data = {'success': True, 'code': response.status_code, - 'current_time': round(time.time()), 'show_type': settings.MESSAGE_SHOW_TYPE['NONE']} - response.data.update(data) + response.data.update(ExceptionHandlerMiddleware.__make_response(204, dict())) elif response.status_code == 403: # Forbidden - data = { - 'errors': response.data, - 'dev_error': { - 'user': request.user.username, 'api': request.path - } - } - response.data = {'success': False, 'message': 'Permission denied', 'code': response.status_code, - 'dev_error': None, 'current_time': round(time.time()), 'errors': None, - 'show_type': settings.MESSAGE_SHOW_TYPE['TOAST']} + # IS NOT USED + # data = { + # 'errors': response.data, + # 'dev_error': { + # 'user': request.user.username, 'api': request.path + # } + # } + response.data = ExceptionHandlerMiddleware.__make_response(403, { + 'message': 'Permission denied', + 'dev_error': None, + 'errors': None, + 'show_type': settings.MESSAGE_SHOW_TYPE['TOAST'] + }) elif response.status_code == 401: # Unauthorized - data = {'errors': response.data['detail'] if 'detail' in response.data else response.data, - 'dev_error': {'user_ip': request.META['REMOTE_ADDR'], 'api_address': request.path}, - 'message': 'Unauthorized access.', 'show_type': settings.MESSAGE_SHOW_TYPE['TOAST']} - - response.data = {'success': False, 'code': response.status_code, - 'current_time': round(time.time())} - response.data.update(data) + response.data = ExceptionHandlerMiddleware.__make_response(401, { + 'errors': response.data.get('detail', response.data), + 'dev_error': + { + 'user_ip': request.META['REMOTE_ADDR'], + 'api_address': request.path + }, + 'message': 'Unauthorized access.', + 'show_type': settings.MESSAGE_SHOW_TYPE['TOAST'] + }) elif response.status_code == 405: # Method Not Allowed - data = { + response.data = ExceptionHandlerMiddleware.__make_response(405, { 'errors': response.data, - 'dev_error': {'user': request.user.username, 'api': request.path}, - 'message': 'Method not allowed', 'show_type': settings.MESSAGE_SHOW_TYPE['NONE'] - } - - response.data = {'success': False, 'code': response.status_code, - 'current_time': round(time.time())} - response.data.update(data) + 'dev_error': { + 'user': request.user.username, + 'api': request.path + }, + 'message': 'Method not allowed' + }) elif response.status_code == 406: # 406 Not Acceptable - data = { - 'errors': response.data, 'message': _('Not Acceptable request, maybe not supported version'), - 'dev_error': {'user': request.user.username, 'api': request.path}, - 'show_type': settings.MESSAGE_SHOW_TYPE['NONE'] - } - - response.data = {'success': False, 'code': response.status_code, - 'current_time': round(time.time())} - response.data.update(data) + response.data = ExceptionHandlerMiddleware.__make_response(406, { + 'errors': response.data, + 'message': _('Not Acceptable request, maybe not supported version'), + 'dev_error': { + 'user': request.user.username, + 'api': request.path + }, + }) + elif response.status_code == 415: # 415 Unsupported media type - data = { - 'errors': response.data, 'message': _('Unsupported media type'), - 'dev_error': {'user': request.user.username, 'api': request.path}, - 'show_type': settings.MESSAGE_SHOW_TYPE['NONE'] - } - - response.data = {'success': False, 'code': response.status_code, - 'current_time': round(time.time())} - response.data.update(data) + response.data = ExceptionHandlerMiddleware.__make_response(415, { + 'errors': response.data, + 'message': _('Unsupported media type'), + 'dev_error': { + 'user': request.user.username, + 'api': request.path + }, + }) elif response.status_code == 400: # Bad Request - error = response.data.pop('dev_error') if 'dev_error' in response.data else None - data = { - 'errors': response.data['non_field_errors'] if 'non_field_errors' in response.data else response.data, - 'dev_error': {'user': request.user.username, 'api_address': request.path, - 'user_ip': request.META['REMOTE_ADDR'], 'error': error}, - 'message': 'Bad request', 'show_type': settings.MESSAGE_SHOW_TYPE['NONE'] - } - response.data = {'success': False, 'code': response.status_code, - 'current_time': round(time.time())} - response.data.update(data) + error = response.data.pop('dev_error', None) + response.data = ExceptionHandlerMiddleware.__make_response(400, { + 'errors': response.data.get('non_field_errors', response.data), + 'dev_error': { + 'user': request.user.username, + 'api_address': request.path, + 'user_ip': request.META['REMOTE_ADDR'], + 'error': error + }, + 'message': 'Bad request' + }) elif response.status_code == 429: - data = { + response.data = ExceptionHandlerMiddleware.__make_response(429, { 'message': response.data['detail'], - 'dev_error': {'user': request.user.username, 'api': request.path}, - 'show_type': settings.MESSAGE_SHOW_TYPE['NONE'] - } - - response.data = {'success': False, 'code': response.status_code, - 'current_time': round(time.time())} - response.data.update(data) - + 'dev_error': { + 'user': request.user.username, + 'api': request.path + }, + }) return response From 62684d2598d7a19ebfada697c59cdcb490a508aa Mon Sep 17 00:00:00 2001 From: 0xNima <79907489+0xNima@users.noreply.github.com> Date: Sun, 9 May 2021 13:16:58 +0430 Subject: [PATCH 2/2] Update responses.py --- utilities/responses.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/utilities/responses.py b/utilities/responses.py index 2942b7f..d84d75c 100644 --- a/utilities/responses.py +++ b/utilities/responses.py @@ -5,6 +5,7 @@ from django.conf import settings from django.utils.translation import ugettext as _ +from rest_framework import status from rest_framework.response import Response @@ -13,7 +14,6 @@ def __init__(self, **kwargs): self.message = kwargs.get('message') self.show_type = kwargs.get('show_type', settings.MESSAGE_SHOW_TYPE['TOAST']) self.current_time = round(time.time()) - self.status = kwargs.get("status") self.success = kwargs.get("success") def send(self): @@ -25,19 +25,21 @@ def send(self): class ErrorResponse(BaseResponse): - def __init__(self, dev_error=None, errors=None, **kwargs): + def __init__(self, message, dev_error=None, errors=None, **kwargs): super().__init__(**kwargs) + self.message = message self.dev_error = dev_error self.errors = errors + self.status = kwargs.get("status", 400) class SuccessResponse(BaseResponse): - def __init__(self, message, data=None, **kwargs): + def __init__(self, data=None, **kwargs): super().__init__(**kwargs) - self.message = message self.data = data self.index = kwargs.get('index') self.total = kwargs.get('total') + self.status = kwargs.get("status", 200) class ExceptionHandlerMiddleware(object): @@ -52,7 +54,7 @@ def __call__(self, request): @staticmethod def __make_response(status_code: int, extra: dict): return { - 'success': True if status_code // 100 == 2 else False, + 'success': status.is_success(status_code), 'code': status_code, 'current_time': round(time.time()), 'show_type': settings.MESSAGE_SHOW_TYPE['NONE'],