Advanced filtering
在这个教程中我们将看下如何使用F这个对象进行高级的主机过滤,让我们从初始化nornir开始然后
看下inventory:
from nornir import InitNornir
from nornir.core.filter import F
nr = InitNornir(config_file="advanced_filtering/config.yaml")
---
%cat advanced_filtering/inventory/hosts.yaml
cat:
groups:
- terrestrial
- mammal
data:
domestic: true
diet: omnivore
additional_data:
lifespan: 17
famous_members:
- garfield
- felix
- grumpy
bat:
groups:
- terrestrial
- mammal
data:
domestic: false
fly: true
diet: carnivore
additional_data:
lifespan: 15
famous_members:
- batman
- count chocula
- nosferatu
eagle:
groups:
- terrestrial
- bird
data:
domestic: false
diet: carnivore
additional_data:
lifespan: 50
famous_members:
- thorondor
- sam
canary:
groups:
- terrestrial
- bird
data:
domestic: true
diet: herbivore
additional_data:
lifespan: 15
famous_members:
- tweetie
caterpillaer:
groups:
- terrestrial
- invertebrate
data:
domestic: false
diet: herbivore
additional_data:
lifespan: 1
famous_members:
- Hookah-Smoking
octopus:
groups:
- marine
- invertebrate
data:
domestic: false
diet: carnivore
additional_data:
lifespan: 1
famous_members:
- sharktopus
%cat advanced_filtering/inventory/groups.yaml
---
mammal:
data:
reproduction: birth
fly: false
bird:
data:
reproduction: eggs
fly: true
invertebrate:
data:
reproduction: mitosis
fly: false
terrestrial: {}
marine: {}
你可以看到我们已经准备了一些拥有不同属性的动物。F对象可以让你访问魔法方法,这些魔法方法都是两个下划线和魔法方法的名称组成的。例如,如果你想检查一个列表里是否包含指定的元素可以通过__contains魔法方法。让我们通过这个特性获取所有属于鸟类的动物:
birds = nr.filter(F(groups__contains="bird"))
print(birds.inventory.hosts.keys())
输出:
dict_keys(['eagle', 'canary'])
我们还可以通过~来进行取反:
birds = nr.filter(~F(groups__contains="bird"))
print(birds.inventory.hosts.keys())
输出:
dict_keys(['cat', 'bat', 'caterpillaer', 'octopus'])
我们还可以复合F对象通过符号&和|来单独执行且和或的操作:
domestic_or_bird = nr.filter(F(groups__contains="bird") | F(domestic=True))
print(domestic_or_bird.inventory.hosts.keys())
输出:
dict_keys(['cat', 'eagle', 'canary'])
domestic_mammals = nr.filter(F(groups__contains="mammal") & F(domestic=True))
print(domestic_mammals.inventory.hosts.keys())
输出:
dict_keys(['cat'])
如你所想,你可以组合所有的符号:
flying_not_carnivore = nr.filter(F(fly=True) & ~F(diet="carnivore"))
print(flying_not_carnivore.inventory.hosts.keys())
输出:
dict_keys(['canary'])
你还可以通过访问魔法方法的方式访问嵌套的数据,通过在你想访问的数据前加两个下划线。你可以根据需求继续建造甚至访问嵌套数据的魔法方法。例如,让我们获取那些寿命大于等于15的动物:
long_lived = nr.filter(F(additional_data__lifespan__ge=15))
print(long_lived.inventory.hosts.keys())
输出:
dict_keys(['cat', 'bat', 'eagle', 'canary'])
还有两个"特殊服务"来帮助你处理lists,any和all。这些方法可以让你发送一个列表的元素来获取那些包含一个或包含全部元素的对象。例如:
marine_and_invertebrates = nr.filter(F(groups__all=["marine", "invertebrate"]))
print(marine_and_invertebrates.inventory.hosts.keys())
输出:
dict_keys(['octopus'])
bird_or_invertebrates = nr.filter(F(groups__any=["bird", "invertebrate"]))
print(bird_or_invertebrates.inventory.hosts.keys())
输出:
dict_keys(['eagle', 'canary', 'caterpillaer', 'octopus'])