瓶中 IP 过滤

IP filtering in bottle

我在 heroku 上有一个 Bottle 应用程序,我需要过滤入站 IP 地址。我不知道该怎么做。

建议使用包装器,但这是针对私有路由的——不过滤入站请求。包装器是:

def private_only(route):
    def wrapper(*args, **kwargs):
        if IPy.IP(bottle.request.remote_addr).iptype() == 'PRIVATE':
            return route(*args, **kwargs)
        else:
            return "Not allowed!"
    return wrapper

将包装器更改为:

def private_only(route):
    def wrapper(*args, **kwargs):
        if IPy.IP(bottle.request.remote_addr).iptype() in ALLOWED_IPS:
            return route(*args, **kwargs)
        else:
            return "Not allowed!"
    return wrapper

并用以下方法装饰路线:

@route('/my/internal/route')
@private_only
def my_view():
    return some_data()

工作?

如果你想为整个 bottle 应用程序启用过滤,我建议改为创建一个插件。下面的示例应该有效:

from bottle import request
from bottle import HTTPError
from bottle import app

class IPFilteringPlugin(object):
    name = 'ipfiltering'
    api = 2

    def __init__(self, allowed_ips=[]):
        self.allowed_ips = allowed_ips

    def apply(self, callback, route):
        def wrapper(*a, **ka):
            if request.remote_addr in self.allowed_ips:
                return callback(*a, **ka)
            raise HTTPError("Permission denied", status=403) 
        return wrapper

app.install(IPFilteringPlugin(["127.0.0.1", "10.0.2.15"])

另请注意,您只能在每个路由中使用此插件,方法是在 @route 定义中指定

filter_internal = IPFilteringPlugin(["127.0.0.1", "10.0.2.15"])
@route('/my/internal/route', apply=filter_internal)
def internal_route(self):
    pass

# or directly route per route
@route('/my/internal/route', apply=IPFilteringPlugin(["127.0.0.1", "10.0.2.15")
def internal_route(self):
    pass