【问题标题】:IP filtering in bottle瓶装IP过滤
【发布时间】:2017-01-20 05:44:33
【问题描述】:

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

工作?

【问题讨论】:

    标签: python routing ip filtering bottle


    【解决方案1】:

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

    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
    

    【讨论】:

    • 很好的建议。我将raise HTTPError("Permission denied", status=403) 更改为raise abort(403, "Access denied")。为了克服 Python 试图在 HTTPError 上执行 ErrorHandling 但这可能是由于我的特定配置。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    相关资源
    最近更新 更多