我正在尝试创建一个将返回True
或False
的函数,具体取决于用户的IP地址是内部还是外部IP地址。我们希望内部用户能够看到更多内容并拥有更多访问权限。我们希望尽可能“廉价”地做到这一点。我知道如何查询通用IP并对元组使用条件逻辑。我想知道的是Django可以为我做大部分工作吗?
示例:
if request.is_internal():
#Do Special Secret Internal Stuff Things!
我已经阅读了一些关于Django的INTERNAL_IPS,但它似乎只用于调试,并且不允许我调用它。我错了吗?
答案 0 :(得分:3)
您最好的选择是创建一个视图装饰器来检查远程地址,然后在远程地址不在settings.INTERNAL_IPS
时引发403,如下所示:
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)