Skip to content

Instantly share code, notes, and snippets.

@stkrp
stkrp / mapping_to_choices.py
Created May 8, 2019 12:54
Converts a mapping to Django field choices
from typing import Any, Mapping, Tuple, Callable
def mapping_to_choices(
mapping: Mapping[str, Any],
label_factory: Callable[[str], Any] = lambda v: v,
recursive: bool = True,
) -> Tuple[Tuple[Any, Any], ...]:
"""
Converts a mapping to Django field choices.
@stkrp
stkrp / multiple_indexes.py
Created May 6, 2019 09:16
Multiple indexes
class multiple_indexes(object):
""" Mixin """
def __getitem__(self, index):
if not isinstance(index, tuple):
index = (index, )
getter = super().__getitem__
retval = []
for i in index:
part = getter(i)
if isinstance(i, slice):
from transformation import pipeline, rename_fields, transform_field_value, replace, group_fields
if __name__ == '__main__':
car_transformer = pipeline(
rename_fields({"owner_yob": "owner_year_of_birth"}),
transform_field_value("owner_year_of_birth", int),
transform_field_value("owner_gender", replace({"female": 0, "male": 1}, None)),
group_fields("owner", ("owner_first_name", "owner_last_name", "owner_year_of_birth", "owner_gender")),
transform_field_value(
@stkrp
stkrp / geos_buffer_with_style.py
Last active January 10, 2018 17:36
Portable version of `django.contrib.gis.geos.geometry.GEOSGeometryBase.buffer_with_style()`
'''
https://code.djangoproject.com/ticket/28960
For Python 2.x you need to delete the annotations and related imports.
'''
from ctypes import c_double, c_int
from django.contrib.gis.geos.libgeos import GEOM_PTR
from django.contrib.gis.geos.prototypes.topology import Topology
@stkrp
stkrp / yandex_tts_client.py
Last active November 22, 2017 13:22
Simple class for synthesis of speech (from text to sound) with Yandex TTS
"""
Required:
* Python 3 (use 3.5+ or remove type hinting)
* requests (`pip3 install requests`)
"""
from typing import Optional
from urllib.parse import urljoin
from requests import Session
@stkrp
stkrp / least_greatest.py
Last active June 15, 2020 19:15
Least and greatest objects in python
class _Singleton(type):
_instances = {}
def __call__(cls, *pargs, **kwargs):
mcls = cls.__class__
if cls not in mcls._instances:
mcls._instances[cls] = super().__call__(*pargs, **kwargs)
return mcls._instances[cls]
@stkrp
stkrp / cache_decorator.py
Created August 11, 2016 11:36
Caching the result of the method call in the instance of the class
from functools import wraps
def cache_to_attr(
cache_attr_name, with_cache_flag_kwarg_name='with_cache',
default_with_cache_value=True,
):
"""
Декоратор, реализующий кэширование результата вызова метода
в атрибут экземпляра
@stkrp
stkrp / getters.py
Created July 18, 2016 18:01
Django model's instances getters
from django.shortcuts import get_object_or_404, _get_queryset
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
__all__ = (
'get_object_or_create', 'get_object_or_404', 'get_object_or_none',
'get_first_or_create', 'get_first_or_404', 'get_first_or_none',
)
@stkrp
stkrp / soft_delete.py
Created July 18, 2016 17:59
Django soft delete pattern
"""
Реализация `Soft delete` (удаления с поддержкой восстановления).
# ================== #
# ===== Пример ===== #
# ================== #
# --- Source: catalog.models --- #
from core.models.mixins import CUDMixin, TitleMixin
from core.models.soft_delete import SoftDeleteMixin
@stkrp
stkrp / ping.py
Last active May 17, 2016 17:03
Simple ping over http
from socket import timeout as TimeoutException
from http.client import HTTPConnection, HTTPException
from time import sleep
from datetime import datetime
DEFAULT_TIMEOUT_SEC = 5
DEFAULT_COUNT = None
DEFAULT_INTERVAL_SEC = 0.5