Skip to content

Instantly share code, notes, and snippets.

View filipeximenes's full-sized avatar

Filipe A Ximenes filipeximenes

View GitHub Profile
@filipeximenes
filipeximenes / lua_script.py
Last active July 14, 2023 16:39
Rate Limite
# Leaky bucket implementation from:
# https://blog.callr.tech/rate-limiting-for-distributed-systems-with-redis-and-lua/
LEAKY_BUCKET_SCRIPT = b"""
local ts = tonumber(ARGV[1]) -- current timestamp
local cps = tonumber(ARGV[2]) -- calls per second
local key = KEYS[1]
-- remove tokens older than 1 second ago
local min = ts - 1
@filipeximenes
filipeximenes / query.py
Created December 24, 2019 15:41
Django AND query
User.objects.filter(
Q(internal_groups__id=1) &
~Q(
enrollments__event__id=15,
enrollments__pre_status=ENROLLMENT_PRE_STATUS.going,
)
)
from django.db import transaction, connection
from events.models import Event
def count_events():
with transaction.atomic():
print(Event.objects.count())
input()
@filipeximenes
filipeximenes / setup.py
Last active August 22, 2018 16:34
How I test my DRF views
# serializers.py
from django.contrib.auth.models import User
from rest_framework import serializers
from bikes.models import Bike
class BikeSerializer(serializers.ModelSerializer):
class Meta:
model = Bike
@filipeximenes
filipeximenes / multiple_db_querying.py
Last active May 11, 2020 08:28
Multitenancy post code examples
spinners = (
Spinner.objects
.using(request.customer.name)
.annotate(
avg_duration=Avg('owned_spinners__spins__duration'))
.order_by('-avg_duration'))
from django.utils import timezone
from myapp.models import Event
class EventListView(generics.ListView):
def get_queryset(self):
now = timezone.now()
upcoming = Event.objects.filter(date__gte=now).order_by('date')
passed = Event.objects.filter(date__lt=now).order_by('-date')
import mock
from django.test import TestCase
from django.contrib.auth.models import User
class EmailTests(TestCase):
def setUp(self):
self.user = User.objects.create(
username='theusername', email='the@email.com',
first_name='Filipe', last_name='Ximenes',
@filipeximenes
filipeximenes / models.py
Last active January 11, 2017 18:12
Django REST Framework tests
from django.db import models
class Bike(models.Model):
COLOR_OPTIONS = (('yellow', 'Yellow'), ('red', 'Red'), ('black', 'Black'))
color = models.CharField(max_length=255, null=True, blank=True,
choices=COLOR_OPTIONS)
size = models.DecimalField(max_digits=4, decimal_places=2, null=True, blank=True)
@filipeximenes
filipeximenes / categorize.py
Last active March 22, 2016 22:36
Categorize
def categorize(lst, attrs):
"""
Generate a dictionary of lists where the keys are generated from
some specified attribute of the items in the list
"""
def dive_in(obj, attrs, index=0):
if not obj or index >= len(attrs):
return obj
new_obj = getattr(obj, attrs[index])
if len(attrs) > 0:
@filipeximenes
filipeximenes / urls.py
Created February 3, 2016 19:15
Django view pattern
url(r'^example/$', 'account.views.example_view', name='user_info'),