Skip to main content

Biblioteca de cache incrivelmente poderosa para Django.

Project description

django-smart-cache

Biblioteca de cache inteligente e automática para Django e Django Rest Framework.

Visão Geral

O django-smart-cache oferece decorators e utilitários para adicionar cache automático em views e viewsets do Django/DRF, invalidando o cache sempre que modelos relacionados sofrem alterações. Ideal para APIs e páginas que precisam de alta performance sem perder a atualização dos dados.

  • Cache automático para views e viewsets
  • Invalidação automática ao alterar modelos relacionados
  • Suporte a autenticação (cache por usuário/token)
  • Fácil integração com projetos Django existentes

Instalação

Requisitos:

  • Python >= 3.8
  • Django == 2.2
  • djangorestframework == 3.10

Instale via pip:

pip install django-smart-cache

Configuração

Adicione django_smart_cache ao seu INSTALLED_APPS:

INSTALLED_APPS = [
    ...
    "django_smart_cache.apps.DjangoSmartCacheConfig",
]

Configure o cache do Django normalmente (exemplo com memória local):

CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
        "LOCATION": "unique-snowflake",
    }
}

Como Usar

Cache em Viewsets (DRF)

from django_smart_cache.viewsets import cache_viewset


@cache_viewset(models=["myapp.MyModel"], timeout=60)
class MyViewSet(viewsets.ModelViewSet):
    ...
  • models: lista de modelos que, ao serem alterados, invalidam o cache.
  • timeout: tempo do cache em segundos (padrão: 900).

Cache em Views (função ou classe)

from django_smart_cache.views import cache_view


@cache_view(models=["myapp.MyModel"], timeout=60)
def minha_view(request):
    ...

Exemplo Completo

from rest_framework import viewsets, serializers
from django_smart_cache.viewsets import cache_viewset
from .models import MyModel


class MySerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = "__all__"


@cache_viewset(models=["myapp.MyModel"], timeout=60)
class MyViewSet(viewsets.ModelViewSet):
    serializer_class = MySerializer
    queryset = MyModel.objects.all()

Funcionamento Interno

  • O decorator gera uma chave de cache única por usuário/token e parâmetros da requisição.
  • O cache é invalidado automaticamente via signals (post_save, post_delete, m2m_changed) dos modelos informados.
  • Suporta cache para métodos list e retrieve em viewsets, e qualquer view baseada em função/classe.

Testes

O projeto já inclui testes automatizados com pytest e pytest-django.

Para rodar os testes:

pytest

Desenvolvimento

  • Código-fonte: src/django_smart_cache/
  • Testes: src/tests/
  • Exemplo de template: src/tests/templates/cached_template.html

Autor

Alan Gomes (alan.gomes.ag28@gmail.com)

Licença

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_smart_cache-0.1.0.tar.gz (15.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_smart_cache-0.1.0-py3-none-any.whl (6.6 kB view details)

Uploaded Python 3

File details

Details for the file django_smart_cache-0.1.0.tar.gz.

File metadata

  • Download URL: django_smart_cache-0.1.0.tar.gz
  • Upload date:
  • Size: 15.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.6.10

File hashes

Hashes for django_smart_cache-0.1.0.tar.gz
Algorithm Hash digest
SHA256 a892f63d3bec4502e64f0fc387588002c7e392ee56a2518f6ad5dbab8e52671e
MD5 b14d074228d4349fd1e8417ae87c2afb
BLAKE2b-256 9b46a9d76e97961cc6b57e43f9e690e1bd0e8bdeaf79adb3788255130c76cf4e

See more details on using hashes here.

File details

Details for the file django_smart_cache-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for django_smart_cache-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 90938e0df97dd439527c3bc98133aa788eb71fbc4103be73feb33657f9b21471
MD5 b83e48cbfae6a63579bef825ccb43345
BLAKE2b-256 bda7867c1b047d9c386b4dbe8d746ce16a7f748755312bba7f8a14f3ed3968e4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page