Skip to content

Instantly share code, notes, and snippets.

View nkhitrov's full-sized avatar
🏠
Elixir/Python Backend Developer

Nick Khitrov nkhitrov

🏠
Elixir/Python Backend Developer
View GitHub Profile
@nkhitrov
nkhitrov / base.py
Created May 22, 2023 19:34
sqlalchemy orm repr
# TODO: fix high memory usage for rich models
class Base:
@classmethod
def get_real_column_name(cls, attr_name: str) -> str:
return getattr(inspect(cls).c, attr_name).name
def __str__(self) -> str:
return self.__repr__()
@nkhitrov
nkhitrov / format.py
Last active May 17, 2023 16:15
loguru_formatter
from loguru import logger
def console_formatter(record) -> str:
# WARNING !!!
# Функция должна возвращать строку, которая содержит только шаблоны для форматирования.
# Если в строку прокидывать значения из record (или еще откуда-либо),
# то loguru может принять их за f-строки и попытается обработать, что приведет к ошибке.
# Например, если нужно достать какое-то значение из поля extra, вместо того чтобы прокидывать его в строку формата,
# нужно прокидывать подстроку вида {extra[тут_ключ]}
@nkhitrov
nkhitrov / Flake8.txt
Created May 3, 2023 23:54 — forked from tossmilestone/Flake8.txt
Flake8 integrated with PyCharm
How to manually setup flake8 as PyCharm external tool
File / Settings / Tools / External Tools / Add
Name: Flake8
Program: $PyInterpreterDirectory$/python
Parameters: -m flake8 --max-complexity 10 --ignore E501 $FilePath$
Working directory: $ProjectFileDir$
Output Filters / Add
Name: Filter 1
@nkhitrov
nkhitrov / threadpool_contextvars.py
Last active May 27, 2023 18:31
ThreadPoolExecutor with contextvars and asyncio
import contextvars
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
current_user = contextvars.ContextVar("ID of current user")
shared_user = contextvars.ContextVar("ID of shared user")
def say_hello():
time.sleep(1)
@nkhitrov
nkhitrov / gunicorn_structlog_setup.py
Created April 18, 2023 18:28 — forked from airhorns/gunicorn_structlog_setup.py
Gunicorn structlog integration
import os
import logging.config
import structlog
from .app import app
timestamper = structlog.processors.TimeStamper(fmt="iso")
pre_chain = [
# Add the log level and a timestamp to the event_dict if the log entry is not from structlog.
structlog.stdlib.add_log_level,
@nkhitrov
nkhitrov / structlog_fastapi.py
Created March 16, 2023 00:04
Structlog FastAPI example
"""
Structlog example configuration with FastAPI.
Features:
- async bound logger
- contextvars to log request-id and other meta data
- custom format for default logging loggers and structlog loggers
"""
import asyncio
import logging
@nkhitrov
nkhitrov / conrurrency.py
Created January 24, 2023 17:33
Python 3.11 asyncio concurrency execution example
import asyncio
async def run_task():
print('run task!')
await asyncio.sleep(3)
print('long task finished!')
async def run_task_error():
@nkhitrov
nkhitrov / async_celery_tasks.py
Created January 11, 2023 18:13
Async celery task with rodi DI example
import asyncio
import functools
from typing import Any, Callable, Optional
from celery import shared_task
from rodi import Container, GetServiceContext
from redis.asyncio.cluster import RedisCluster
from sqlalchemy.ext.asyncio import AsyncSession
@nkhitrov
nkhitrov / schemas.py
Created August 24, 2022 20:31
FastAPI generic request, response schemas
from typing import Any, Generic, Type, TypeAlias, TypeVar
from fastapi import status as http_status_code
from pydantic import Field
from pydantic.generics import GenericModel
_Model = TypeVar("_Model")
GenericResponse: TypeAlias = GenericModel
@nkhitrov
nkhitrov / install.sh
Created April 27, 2021 21:05
python virtualenv wrapper install script
pip install virtualenv virtualenvwrapper
sudo echo '# where to store our virtual envs
export WORKON_HOME=$HOME/.pythonvenvs
# where is the virtualenvwrapper.sh
source $(which virtualenvwrapper.sh)
' >> ~/.bashrc
source ~/.bashrc