Skip to content

Instantly share code, notes, and snippets.

@maksjood
maksjood / gist:c9c657c447939e02fe64ffbcae46b0ba
Created April 14, 2024 05:51
healthcheck.io python interface
from enum import Enum
import logging
import requests
logger = logging.getLogger(__name__)
class HealthCheck:
def __init__(self, ping_url:str, time_out:int=30) -> None:
self.ping_url = ping_url
@maksjood
maksjood / gist:382ac267b83666818e33deb17573f4b1
Created January 8, 2024 14:17
Django+PostgreSQL, weighted, fool-proof search
def annotate_for_search(
queryset: QuerySet,
seach_value: str,
fields_weights_map: Dict[str, float],
annotation_name='search_rank',
order_descending_by_rank=True,
exclude_non_matched=False
):
'''
Annotates the `queryset` with relevancy of each row to the `search_value`.
sudo apt-get install graphviz
poetry add pydotplus django-extensions
INSTALLED_APPS = (
...
'django_extensions',
...
)
python manage.py graph_models -a -o myapp_models.png
@maksjood
maksjood / django_config_model.py
Last active April 13, 2023 08:12
a basic model to be used as configuration for a django project
from django.db import models
from django.core.cache import cache
class Config(models.Model):
CACHE_KEY = 'project_config'
class Meta:
ordering = ['id']
def save(self, *args, **kwargs):
@maksjood
maksjood / json_cache.py
Last active March 23, 2023 17:52
a very simple database for very small python projects
from dataclasses import dataclass, asdict
import json
@dataclass
class Cache:
'''this class is used as the database'''
some_field: int
@staticmethod
@maksjood
maksjood / django_choice.py
Last active March 19, 2023 12:47
A class to simplify usage of choices in django model fields. This class can actually be used as small database.
from typing import List, Iterable
class DjangoChoice:
"""A class to simplify usage of choices in django model fields. This class can actually be used as small database."""
def get_attr_dict(self):
res = dict()
for atr in type(self).__dict__.keys():
if not atr.startswith("_"):
@maksjood
maksjood / log_with_args.py
Created January 5, 2023 13:05
a wrapper for a function to get a detailed log for every call and its results
import functools
def log_with_args(logger):
def dec(f0):
@functools.wraps(f0)
def wrapper(*args, **kwargs):
called_with = list(zip(f0.__code__.co_varnames, args)) + list(kwargs.items())
called_with = [f'{v1}={v2}' for v1, v2 in called_with]
called_with = ', '.join(called_with)
logger.info(f'received {f0.__name__} with {called_with}')
# pip install django-admin-rangefilter
from rangefilter.filters import NumericRangeFilter
from django.utils import timezone
class MinutesSinceRangeFilter(NumericRangeFilter):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.title = f'minutes since {self.title}'