Different type of anonymous users with Django -
the django project i'm working on website should accessed local network , internet. , part of content should available anonymous users if visit site local network (basically it's test on ip address), while authenticated users have access whole content.
i though checking ip as described here, seems me quite bad check ip each time user loads page.
is there way cleanly store user data on anonymous user ? nice able use decorator @login_required
, redirect if anonymous user has external ip.
actually, checking ip on every requests seems me 1 of fastest methods available. consider ip loaded in memory on every request, have simple dictionary lookup , comparison, conditional string split/additional dict lookup. compared happens on simplest page views, performance impact neglectable , comparable impact of using sessions or other mechanism save ip.
you can write own decorator function using user_passes_test
:
from django.contrib.auth.decorators import user_passes_test django.utils.decorators import available_attrs functools import wraps local_ips = ( '127.0.0.1', 'other_ip', 'etc.', ) def is_local_request(request): x_forwarded_for = request.meta.get('http_x_forwarded_for') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.meta.get('remote_addr') return ip in local_ips def local_ip_required(view_func): def wrapped_view(request, *args, **kwargs): if not is_local_request(request): raise http404 # or permissiondenied or redirect return view_func(request, *args, **kwargs) return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
then use @local_ip_required. note implementation prevent both anonymous , logged-in users accessing view external location.
Comments
Post a Comment