使用 factory_boy 和 faker 为 django 模型生成特定子网的 Ipv4 地址
Generate Ipv4 address of a specific subnet with factory_boy and faker for django model
大家好!
下面是一个使用 faker 填充模型的脚本。
Faker 允许使用 'address_class' 参数。指定 address_class='a' 会缩小范围,但仅限于 10.0.0.0/8。如何进一步调整生成器,例如调整到 10.10.10.0/24?
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
django.setup()
from workplace.models import IpAddress
import factory
import faker
from faker.providers import internet
faker = faker.Factory.create()
class IpAddressFactory(factory.django.DjangoModelFactory):
class Meta:
model = IpAddress
django_get_or_create = ('ip_address',)
ip_address = faker.ipv4_private(address_class='a')
ip = IpAddressFactory()
print(ip)
ipv4_private
从 providers.internet
使用 class _IPv4Constants._private_networks
调整 class IPv4Constants
中的 _private_networks
就可以了
/lib/python3.7/site-packages/faker/providers/internet/init.py`
class _IPv4Constants:
"""
IPv4 network constants used to group networks into different categories.
Structure derived from `ipaddress._IPv4Constants`.
Excluded network list is updated to comply with current IANA list of
private and reserved networks.
"""
# Three common private networks from class A, B and CIDR
# to generate private addresses from.
_private_networks = [
# ip_network('10.0.0.0/8'),
# ip_network('172.16.0.0/12'),
# ip_network('192.168.0.0/16'),
ip_network('10.10.10.0/24'),
]
大家好!
下面是一个使用 faker 填充模型的脚本。 Faker 允许使用 'address_class' 参数。指定 address_class='a' 会缩小范围,但仅限于 10.0.0.0/8。如何进一步调整生成器,例如调整到 10.10.10.0/24?
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
django.setup()
from workplace.models import IpAddress
import factory
import faker
from faker.providers import internet
faker = faker.Factory.create()
class IpAddressFactory(factory.django.DjangoModelFactory):
class Meta:
model = IpAddress
django_get_or_create = ('ip_address',)
ip_address = faker.ipv4_private(address_class='a')
ip = IpAddressFactory()
print(ip)
ipv4_private
从 providers.internet
_IPv4Constants._private_networks
调整 class IPv4Constants
中的 _private_networks
就可以了
/lib/python3.7/site-packages/faker/providers/internet/init.py`
class _IPv4Constants:
"""
IPv4 network constants used to group networks into different categories.
Structure derived from `ipaddress._IPv4Constants`.
Excluded network list is updated to comply with current IANA list of
private and reserved networks.
"""
# Three common private networks from class A, B and CIDR
# to generate private addresses from.
_private_networks = [
# ip_network('10.0.0.0/8'),
# ip_network('172.16.0.0/12'),
# ip_network('192.168.0.0/16'),
ip_network('10.10.10.0/24'),
]