Not a duplicate of Making random phone number xxx-xxx-xxxx
My project uses python-phonenumbers and django-phonenumber-field for phone number validation. Within the project are vast lists of custom validation rules, for which naive approach like this will not be sufficient:
>>> import functools
>>> import random
>>> a = functools.partial(random.randint, 0, 9)
>>> gen = lambda: "+{}-{}{}{}-{}{}{}-{}{}{}{}".format(a(), a(), a(), a(), a(), a(), a(), a(), a(), a(), a())
>>> gen()
'+2-758-702-0180' # Obviously wrong
>>> gen()
'+1-911-555-0180' # Obviously wrong, it has 911 in it
So, without resorting to a brute-force while loop that has no upper bound, and without introducing an upper bound for such trivial problems, what better ways are there to generate valid phone numbers accepted by the validator itself?
from phonenumber_field.validators import validate_international_phonenumber
from django.core.exceptions import ValidationError
def generate_valid_number():
while True: # While loops are not desired, even with an upper bound!
try:
number = gen()
validate_international_phonenumber(number)
return number
except ValidationError:
pass
We will use the random library to generate random numbers. The number should contain 10 digits. The first digit should start with 9 or 8 or 7 or 6, we will use randint() method. The remaining 9 digits will also be generated using the randint() method.
Use randint() Generate random integer randint() function to get a random integer number from the inclusive range. For example, random. randint(0, 10) will return a random number from [0, 1, 2, 3, 4, 5, 6, 7, 8 ,9, 10].
randrange function. For example import random; print random. randrange(10, 25, 5) prints a number that is between 10 and 25 (10 included, 25 excluded) and is a multiple of 5. So it would print 10, 15, or 20.
If you're using the package faker
you can write a custom provider that can be re-used across your project.
import phonenumbers
from faker.providers.phone_number.en_US import Provider
class CustomPhoneProvider(Provider):
def phone_number(self):
while True:
phone_number = self.numerify(self.random_element(self.formats))
parsed_number = phonenumbers.parse(phone_number, 'US')
if phonenumbers.is_valid_number(parsed_number):
return phonenumbers.format_number(
parsed_number,
phonenumbers.PhoneNumberFormat.E164
)
Used with factory_boy
:
import factory
from faker import Faker
from .models import User
from .providers import CustomPhoneProvider
fake = Faker()
fake.add_provider(CustomPhoneProvider)
class UserFactory(factory.DjangoModelFactory):
class Meta:
model = User
first_name = factory.Faker('first_name')
last_name = factory.Faker('last_name')
phone_number = factory.LazyAttribute(lambda _: fake.phone_number())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With