Skip to content

Commit

Permalink
Cache lookups.
Browse files Browse the repository at this point in the history
Fixes #3.
  • Loading branch information
philipn committed Feb 20, 2015
1 parent d15087f commit c332374
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
7 changes: 6 additions & 1 deletion block_ip/middleware.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from django.http import HttpResponseForbidden
from django.conf import settings
from django.core.cache import cache

from models import BlockIP

Expand All @@ -22,7 +23,11 @@ def process_request(self, request):
ip = get_ip(request)
# TODO: Look into something more optimized for large numbers
# of blocks. https://github.com/jimfunk/django-postgresql-netfields
deny_ips = [i.get_network() for i in BlockIP.objects.all()]
block_ips = cache.get('blockip:list')

This comment has been minimized.

Copy link
@rbtsolis

rbtsolis Mar 21, 2018

Contributor

I try it but i doesn't work very well, because sometimes the blocked user can see the content

if block_ips is None:
block_ips = BlockIP.objects.all()
cache.set('blockip:list', block_ips)
deny_ips = [i.get_network() for i in block_ips]

for net in deny_ips:
if ip in net:
Expand Down
10 changes: 10 additions & 0 deletions block_ip/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.cache import cache
from django.db.models.signals import post_save, post_delete


class BlockIP(models.Model):
Expand All @@ -17,3 +19,11 @@ def get_network(self):
class Meta:
verbose_name = _('IPs & masks to ban')
verbose_name_plural = _('IPs & masks to ban')


def _clear_cache(sender, instance, **kwargs):
cache.set('blockip:list', BlockIP.objects.all())


post_save.connect(_clear_cache, sender=BlockIP)
post_delete.connect(_clear_cache, sender=BlockIP)

0 comments on commit c332374

Please sign in to comment.