3

I am trying to create a function that will return True or False depending on if the ip address of the user is an internal or external IP address. We would like internal users to be able to see more things and have more access. We're looking to do this as 'inexpensively' as possible. I know how to query the general IP and use conditional logic against a tuple. What I'm wondering is can Django do most of this for me?

Example:

if request.is_internal():
    #Do Special Secret Internal Stuff Things!

I've read a bit about Django's INTERNAL_IPS but it seems to only be used for debugging, and will not allow me to call it. Am I wrong on that?

4

1 回答 1

4

最好的办法是创建一个视图装饰器来检查远程地址,然后在远程地址不在时引发 403 settings.INTERNAL_IPS,如下所示:

import functools

from django.conf import settings
from django import http
from django.utils.decorators import method_decorator


def internal_or_403(view_func):
    """
    A view decorator which returns the provided view function,
    modified to return a 403 when the remote address is not in
    the list of internal IPs defined in settings.
    """
    @functools.wraps(view_func)
    def wrapper(request, *args, **kwargs):
        if not request.META['REMOTE_ADDR'] not in settings.INTERNAL_IPS:
            return http.HttpResponseForbidden('<h1>Forbidden</h1>')
        return view_func(request, *args, **kwargs)
    return wrapper


class Internal(object):
    """
    A mix-in for class based views, which disallows requests from
    non-internal IPs.
    """
    @method_decorator(internal_or_403)
    def dispatch(self, *args, **kwargs):
        return super(Internal, self).dispatch(*args, **kwargs)
于 2013-07-10T15:42:18.220 回答