瓶中的IP过滤

时间:2017-01-19 10:52:30

标签: python routing ip filtering bottle

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

This answer建议使用包装器,但这适用于私有路由 - 不过滤入站请求。包装器是:

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()

工作?

1 个答案:

答案 0 :(得分:2)

如果要为整个瓶子应用程序启用过滤,我建议改为创建一个插件。以下示例应该有效:

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