django - 使用 Django 检查内部 IP

标签 django ip

我正在尝试创建一个函数,根据用户的 IP 地址是内部还是外部 IP 地址,该函数将返回 TrueFalse。我们希望内部用户能够看到更多的东西并拥有更多的访问权限。我们希望尽可能“便宜”地做到这一点。我知道如何查询通用 IP 并对元组使用条件逻辑。我想知道 Django 可以为我完成大部分工作吗?

示例:

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

我读过一些关于 Django 的 INTERNAL_IPS但它似乎只用于调试,不允许我调用它。我这样说有错吗?

最佳答案

最好的选择是创建一个 View 装饰器来检查远程地址,然后在远程地址不在 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)

关于django - 使用 Django 检查内部 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17574610/

相关文章:

css - 模板不加载静态文件

Django url反向: Non-reversible reg-exp portion: '(?='

javascript - 服务人员和 Django

node.js - 在 Node 前面使用nginx服务器作为代理时如何获取客户端真实IP

c# - 无法使用套接字连接到我的 IP

ip - 当 TTL 变为 0 时谁丢弃 IP 数据包

python - Django 模板 : Passing a variable from an include, 进入点符号路径

python - Apache 上的 Django 网站,wsgi 失败

c# - 如果需要很多时间,请跳到下一次迭代 c#

ubuntu - 从外部 IP 地址访问主机