Skip to content

Instantly share code, notes, and snippets.

View IamMiracleAlex's full-sized avatar

Miracle Alex IamMiracleAlex

View GitHub Profile
@IamMiracleAlex
IamMiracleAlex / generate_unique_id.py
Created February 27, 2023 22:56
Generate unique id for a model field -- regenerate if id exists
import string
import random
from django.db import models
def generate_random_number(len: int):
return "".join(
random.choice(string.ascii_lowercase + string.digits) for _ in range(len)
)
@IamMiracleAlex
IamMiracleAlex / create_snapshots.py
Created February 27, 2023 22:20
Move or sync database database in production to staging for testing (both database in different AWS accounts and VPCs)
import time
from datetime import datetime
import os
import boto3
from botocore.exceptions import WaiterError
from botocore.waiter import create_waiter_with_client
from celery import shared_task
from .custom_waiter import waiter_model
@IamMiracleAlex
IamMiracleAlex / migrate_data.py
Created February 27, 2023 21:37
Migrate model (Table) data from one database to another database in chunks
import sys
from django.core import serializers
def migrate(model, dest_db, size=2000, start=0, old_db="default"):
"""
Migrate data from one database to another database in chunks
Args:
@IamMiracleAlex
IamMiracleAlex / custom_response.py
Created February 27, 2023 21:00
Standardise api responses to be consistent across board
from collections import OrderedDict
from rest_framework.response import Response
from rest_framework import status
from rest_framework.renderers import JSONRenderer
class SuccessResponse:
'''Standardise API Responses and add additional keys'''
@IamMiracleAlex
IamMiracleAlex / calculate_size.py
Created February 27, 2023 20:48
Calculates storage size and returns the value
def calculate_size(size):
"""
Calculates storage size and returns the value
A single record is 1kb
"""
for x in ["KB", "MB", "GB", "TB"]:
if size < 1000.0:
return "%3.1f %s" % (size, x)
size /= 1000.0
@IamMiracleAlex
IamMiracleAlex / image_to_base64.py
Created February 27, 2023 12:26
Convert an image to base64 string and convert base64 string to a django image
import base64
from django.core.files.uploadedfile import SimpleUploadedFile
def image_to_base64(image) -> str:
"""Converts image to base64 string"""
return base64.b64encode(image.read()).decode()
@IamMiracleAlex
IamMiracleAlex / data_export_util.py
Created February 27, 2023 11:55
This class creates and export reports to csv, html, pdf and xlsx
from typing import Union
import csv
from django.http import HttpResponse
from django.db.models import QuerySet
from rest_framework.response import Response
from xhtml2pdf import pisa
import pandas as pd