Skip to content

Instantly share code, notes, and snippets.

@IlianIliev
IlianIliev / interceptor.py
Created May 10, 2024 07:23
gRPC interceptor to manage Django DB connections
"""
Handling database connections in gRPC server and Django
As explained in the docs -> https://docs.djangoproject.com/en/5.0/ref/databases/#caveats
```
If a connection is created in a long-running process, outside of Django’s request-response cycle, the connection will
remain open until explicitly closed, or timeout occurs.
```
This practically means that all long-running processes are responsible for managing their database connections.
# AAA - Triple A is the base of testing. It stands for Arrange, Act, Assert
# Ако правилно съм разбрал правиш някакъв тул за автоматизация.
# Да кажем, че имаш някакъв сет от лампи и искаш да напишеш метод който
# проверява колко лампи са светнати в даден момент
class Lamp:
pass
import logging
import sys
logging.basicConfig(filename='mybot.log', level=logging.DEBUG,
format='%(asctime)s: %(name)s: %(levelname)s: %(message)s')
logger = logging.getLogger(__name__)
logger.info('Start')
from django.db import models
from django.db.models import Avg
class Blog(models.Model):
name = models.CharField(max_length=100)
rating = models.DecimalField(max_digits=5, decimal_places=2, null=True)
def __str__(self):
return self.name
@IlianIliev
IlianIliev / utils.py
Last active September 11, 2018 15:41
Extended class for DRF tests
from django.test import TestCase
from rest_framework.test import APIClient, APIRequestFactory
from users.factories import UserFactory
API_BASE_URL = 'api'
REQUEST_FACTORY = APIRequestFactory()
@IlianIliev
IlianIliev / django_test_runner.py
Created December 13, 2017 10:27
PyCharm Django Test Runner fix for Django 2.0
from tcunittest import TeamcityTestRunner, TeamcityTestResult
from tcmessages import TeamcityServiceMessages
import sys
from pycharm_run_utils import adjust_django_sys_path
from django.test.utils import get_runner
adjust_django_sys_path()
from django.conf import settings
@IlianIliev
IlianIliev / f.py
Created July 13, 2017 16:25
Fibonacci without recursion
def fib(n, start_sequence=None):
if not start_sequence:
start_sequence = [0, 1]
res = 0
for i in range(0, n-1): # -1 to as we count the start sequence as the first two numbers
res = sum(start_sequence)
start_sequence.pop(0)
start_sequence.append(res)
# Dockerfile
FROM python:3.5
ENV PYTHONUNBUFFERED 1
ADD . /<project>
WORKDIR /<project>
RUN pip install -r requirements.txt
# docker-compose.yml
version: '3'
from django.core.cache import cache
def get_my_choices():
key = 'my-dynamic-choices-key'
res = cache.get(key)
if not res:
# we are casting to list here so we store a list in the cache, not a QuerySet instance)
res = list(User.objects.values_list('id', 'email')) # this is just an example replace it with your model/fields
cache.set(key, res, 60*60*24) # cache for a day
@IlianIliev
IlianIliev / fields.py
Last active September 10, 2015 11:05
DynamicChoiceField for Django REST Framework 3.x
class DynamicChoiceField(ChoiceField):
""" Privides set_choices method used to update all choice related attributes of the field """
def set_choices(self, choices):
""" Unfortunately just setting field.choices is not enough so we will sue this class to update evverything """
self.grouped_choices = to_choices_dict(choices)
self.choices = flatten_choices_dict(self.grouped_choices)
self.choice_strings_to_values = dict([
(six.text_type(key), key) for key in self.choices.keys()