如何在瓶中按路线过滤IP地址? [英] How to filter IP addresses by route in bottle?

查看:72
本文介绍了如何在瓶中按路线过滤IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网络服务器提供了几种服务(路线)。其中某些必须限制为私有IP( RFC1918 )IP,而另一些则同时服务于私有IP和公共IP。 。

My bottle webserver provides several services (routes). Some of them must be restricted to private (RFC1918) IPs, while others serve both private and public ones.

现在我在路线的开头检查

Right now I check at the beginning of the routes

if IPy.IP(bottle.request.remote_addr).iptype() == 'PRIVATE':
    # code for private service

我需要针对仅限于私有IP的每条路由进行检查(10种情况,并且还在增长),而对于私有和公共IP的路由则不需要进行检查(1种情况)。

I need to check this for each route restricted to private IPs (10 cases and growing) and do not need to do that for the private and public ones (1 case).

是否存在可以添加决策树的全局路由过滤器?

我专门在python应用程序中寻找实现该目标的方法,而不是通过例如上游过滤反向代理。

I am specifically looking for a way to to that in the python application, and not through e.g. an upstream filtering reverse proxy.

推荐答案

我不知道内置的任何内容,但是可以使用装饰器。从装饰器返回包装器,该装饰器执行IP类型检查,如果检查通过则返回常规视图,否则返回错误消息(或类似消息)。
以下应该起作用:

I'm not aware of anything built in, but you could use a decorator to do that. Return a wrapper from the decorator, which performs the check for the IP type and returns the regular view if the check passes or an error-message (or similar) otherwise. The following should work:

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

然后用它装饰您的私密视图:

Then decorate your private views with it:

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

这篇关于如何在瓶中按路线过滤IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆