Python 瓶内IP过滤

Python 瓶内IP过滤,python,routing,ip,filtering,bottle,Python,Routing,Ip,Filtering,Bottle,我在heroku上有一个瓶子应用程序,我需要过滤入站IP地址。我不知道怎么做 建议使用包装器,但这适用于专用路由,而不是过滤入站请求。包装是: def private_only(route): def wrapper(*args, **kwargs): if IPy.IP(bottle.request.remote_addr).iptype() == 'PRIVATE': return route(*args, **kwargs)

我在heroku上有一个瓶子应用程序,我需要过滤入站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()

工作?

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

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

很好的建议。我将
raisehttperror(“权限被拒绝”,状态=403)
更改为
raiseabort(403,“访问被拒绝”)
。为了克服Python试图在HTTPError上执行错误处理的问题,这可能是由于我的特定配置。