Skip to content

Instantly share code, notes, and snippets.

View AlonsoMackenlly's full-sized avatar
🗻
A happy life begins with peace of mind.

AlonsoMackenlly AlonsoMackenlly

🗻
A happy life begins with peace of mind.
View GitHub Profile
@AlonsoMackenlly
AlonsoMackenlly / pytest_conftest.py
Last active March 5, 2025 12:57
PyCharm pytest verbose of nodes names by docstring
def pytest_itemcollected(item):
"""Модифицирует название теста при сборке."""
if isinstance(item, pytest.Function): # Проверяем, что это тестовая функция
class_doc = item.parent.obj.__doc__.strip() if item.parent.obj.__doc__ else ""
method_doc = item.obj.__doc__.strip() if item.obj.__doc__ else ""
if class_doc and method_doc:
# Используем описание класса и метода
item._nodeid = f"{class_doc} | {item.parent.obj.__name__}::{method_doc}"
elif method_doc:
@AlonsoMackenlly
AlonsoMackenlly / settings_logging.py
Last active December 2, 2023 17:47
Loguru with Django
class InterceptHandler(logging.Handler):
def emit(self, record):
# Get corresponding Loguru level if it exists
try:
level = logger.level(record.levelname).name
except ValueError:
level = record.levelno
# Find caller from where originated the logged message
@AlonsoMackenlly
AlonsoMackenlly / setup_console.py
Last active October 17, 2022 06:46
Устанавливает кодировку принтов в консоли (JetBrains иногда неверно определяет кодировку, из за этого в консоли каракули у кириллицы)
def setup_console(sys_enc="utf-8"):
reload(sys)
try:
# для win32 вызываем системную библиотечную функцию
if sys.platform.startswith("win"):
import ctypes
enc = "cp%d" % ctypes.windll.kernel32.GetOEMCP() #TODO: проверить на win64/python64
else:
# для Linux всё, кажется, есть и так
enc = (sys.stdout.encoding if sys.stdout.isatty() else
@AlonsoMackenlly
AlonsoMackenlly / _WebStorm Babel file-watcher setup basics.md
Created February 11, 2022 08:17
WebStorm/PHPStorm (and so on...) Babel file-watcher setup basics

Basic Babel file-watcher setup

This requires NPM to be installed.

Adding file-watchers

package.json file

If your project does not already have a 'package.json' file; run:

@AlonsoMackenlly
AlonsoMackenlly / celery.sh
Created June 29, 2021 12:31
Команды для celery
/* Useful celery config.
app = Celery('tasks',
broker='redis://localhost:6379',
backend='redis://localhost:6379')
app.conf.update(
CELERY_TASK_RESULT_EXPIRES=3600,
CELERY_QUEUES=(
Queue('default', routing_key='tasks.#'),
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericRelation
# создадим класс, хранящий множество записей, которые могут привязываться к разным моделями
class Accumulator(models.Model):
# Ссылка на встроенную модель, где фигурируют все модели всех зарегистрированных приложений
content_type = models.ForeignKey(ContentType, on_delete = models.PROTECT, editable = False, db_index = True)
function dump_debug($input, $collapse=false) {
$recursive = function($data, $level=0) use (&$recursive, $collapse) {
global $argv;
$isTerminal = isset($argv);
if (!$isTerminal && $level == 0 && !defined("DUMP_DEBUG_SCRIPT")) {
define("DUMP_DEBUG_SCRIPT", true);
echo '<script language="Javascript">function toggleDisplay(id) {';
@AlonsoMackenlly
AlonsoMackenlly / imports.py
Created February 9, 2021 06:10
Импорт класса по строковому пути к модулю
import importlib
from typing import Any, Optional
def import_class_by_path(path: str) -> Optional[Any]:
""" Делает динамический импорт класса по пути типа apps.app.lib.classes.MyClass """
# Разбиваем модули на куски
modules = path.split('.')
# Берем конечный модуль из которого импортируем класс
@AlonsoMackenlly
AlonsoMackenlly / singleton.py
Created February 9, 2021 06:08
Sigleton class decorator python
def singleton(class_):
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
@AlonsoMackenlly
AlonsoMackenlly / originate.py
Last active December 2, 2020 13:21
Оригинация звонка через Asterisk Freebpx ARI с помощью библиотеки ari-py (https://github.com/asterisk/ari-py). Важно! Для запуска кода необходимо иметь Python 2 версии!
# coding=utf-8
# Пример диалплана
# [custom-context]
# same => n,Answer()
# exten => _XXXX.,n,Stasis(ari_test)
# ;exten => _XXXX.,n,Dial(${TDIAL_STRING}/${OUTNUM}${TDIAL_SUFFIX},${TRUNK_RING_TIMER},${DIAL_TRUNK_OPTIONS})
# exten => _XXXX.,n,NoOp(Left Stasis)
# exten => _XXXX.,n,Hangup