Files
digest_app/module_project/utils.py

78 lines
2.6 KiB
Python
Raw Normal View History

2024-02-26 13:28:32 +05:30
from rest_framework.response import Response
from rest_framework.exceptions import NotFound
from django.http import JsonResponse
from . import constants
from rest_framework import status
import string
import random
import logging
import os
import stat
class GroupWriteRotatingFileHandler(logging.handlers.RotatingFileHandler):
def doRollover(self):
"""
Overrides base class method to make the new log file group writable.
"""
# Rotate the file first.
logging.handlers.RotatingFileHandler.doRollover(self)
# Add group write to the current permissions.
currMode = os.stat(self.baseFilename).st_mode
os.chmod(self.baseFilename, currMode | stat.S_IWGRP)
class ApiResponse:
@staticmethod
def success(message, data=None, status=status.HTTP_200_OK):
response_data = {"success": True, "status": status, "message": message}
if data is not None:
response_data["data"] = data
return Response(response_data, status=status)
@staticmethod
def error(message, errors=None, status=status.HTTP_403_FORBIDDEN):
response_data = {"success": False, "status": status, "message": message}
if errors is not None:
response_data["errors"] = errors
return Response(response_data, status=status)
# @staticmethod
# def validation_error(errors, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY):
# return ApiResponse.error("Validation error", errors, status_code)
class JsonResponseUtil:
@staticmethod
def success(message, data=None, status_code=200):
response_data = {"success": True, "status": status_code, "message": message}
if data is not None:
response_data["data"] = data
return JsonResponse(response_data, status=status_code)
@staticmethod
def error(message, errors=None, status_code=403):
response_data = {"success": False, "status": status_code, "message": message}
if errors is not None:
response_data["errors"] = errors
return JsonResponse(response_data, status=status_code)
class RandomGenerator:
@staticmethod
def number(start, end):
# import random
return random.randint(start, end)
@staticmethod
def password_reset_code():
return RandomGenerator.number(10000000, 99999999)
def random_otp():
return RandomGenerator.number(1000, 9999)
@staticmethod
def random_alphnum(length):
return "".join(
random.choice(string.ascii_uppercase + string.digits) for _ in range(length)
)