How to use the phonenumbers.PhoneNumberFormat.E164 function in phonenumbers

To help you get started, we’ve selected a few phonenumbers examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github matrix-org / sydent / sydent / validators / msisdnvalidator.py View on Github external
origs = [{
            "type": "alpha",
            "text": "Matrix",
        }]
        if countryCode in self.originators:
            origs = self.originators[countryCode]
        elif 'default' in self.originators:
            origs = self.originators['default']

        # deterministically pick an originator from the list of possible
        # originators, so if someone requests multiple codes, they come from
        # a consistent number (if there's any chance that some originators are
        # more likley to work than others, we may want to change, but it feels
        # like this should be something other than just picking one randomly).
        msisdn = phonenumbers.format_number(
            destPhoneNumber, phonenumbers.PhoneNumberFormat.E164
        )[1:]
        return origs[sum([int(i) for i in msisdn]) % len(origs)]
github django-oscar / django-oscar / src / oscar / core / phonenumber.py View on Github external
from django.core import validators
from django.core.exceptions import ValidationError
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _


@python_2_unicode_compatible
class PhoneNumber(phonenumbers.phonenumber.PhoneNumber):
    """
    A extended version of phonenumbers.phonenumber.PhoneNumber that provides
    some neat and more pythonic, easy to access methods. This makes using a
    PhoneNumber instance much easier, especially in templates and such.
    """
    format_map = {
        'E164': phonenumbers.PhoneNumberFormat.E164,
        'INTERNATIONAL': phonenumbers.PhoneNumberFormat.INTERNATIONAL,
        'NATIONAL': phonenumbers.PhoneNumberFormat.NATIONAL,
        'RFC3966': phonenumbers.PhoneNumberFormat.RFC3966,
    }

    @classmethod
    def from_string(cls, phone_number, region=None):
        phone_number_obj = cls()
        if region is None:
            region = getattr(settings, 'PHONENUMBER_DEFAULT_REGION', None)
        phonenumbers.parse(number=phone_number, region=region,
                           keep_raw_input=True, numobj=phone_number_obj)
        return phone_number_obj

    def __str__(self):
        format_string = getattr(
github mattrobenolt / sentry-twilio / sentry_twilio / models.py View on Github external
def clean_phone(phone):
    # This could raise, but should have been checked with validate_phone first
    return phonenumbers.format_number(
        phonenumbers.parse(phone, DEFAULT_REGION),
        phonenumbers.PhoneNumberFormat.E164,
    )
github alephdata / followthemoney / followthemoney / types / phone.py View on Github external
def clean_text(self, number, proxy=None, **kwargs):
        for num in self._parse_number(number, proxy=proxy):
            if is_valid_number(num):
                return format_number(num, PhoneNumberFormat.E164)
github CroceRossaItaliana / jorvik / anagrafica / models.py View on Github external
def aggiungi_numero_telefono(self, numero, servizio=False, paese="IT"):
        """
        Aggiunge un numero di telefono per la persona.
        :param numero: Il numero di telefono.
        :param servizio: Vero se il numero e' di servizio. Default False.
        :param paese: Suggerimento per il paese. Default "IT".
        :return: True se l'inserimento funziona, False se il numero e' mal formattato.
        """
        try:
            n = phonenumbers.parse(numero, paese)
        except phonenumbers.phonenumberutil.NumberParseException:
            return False
        f = phonenumbers.format_number(n, phonenumbers.PhoneNumberFormat.E164)
        t = Telefono(persona=self, numero=f, servizio=servizio)
        try:
            t.save()
        except:
            return False
        return True
github Bouke / django-two-factor-auth / two_factor / migrations / 0003_auto_20150817_1733.py View on Github external
def migrate_phone_numbers(apps, schema_editor):
    PhoneDevice = apps.get_model("two_factor", "PhoneDevice")
    for device in PhoneDevice.objects.all():
        username = device.user.get_username()
        try:
            number = phonenumbers.parse(device.number)
            if not phonenumbers.is_valid_number(number):
                logger.info("User '%s' has an invalid phone number '%s'." % (username, device.number))
            device.number = phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164)
            device.save()
        except phonenumbers.NumberParseException as e:
            # Do not modify/delete the device, as it worked before. However this might result in issues elsewhere,
            # so do log a warning.
            logger.warning("User '%s' has an invalid phone number '%s': %s. Please resolve this issue, "
                           "as it might result in errors." % (username, device.number, e))
github matrix-org / sydent / sydent / validators / msisdnvalidator.py View on Github external
def requestToken(self, phoneNumber, clientSecret, sendAttempt, nextLink):
        if str(phoneNumber.country_code) in self.smsRules:
            action = self.smsRules[str(phoneNumber.country_code)]
            if action == 'reject':
                raise DestinationRejectedException()

        valSessionStore = ThreePidValSessionStore(self.sydent)

        msisdn = phonenumbers.format_number(
            phoneNumber, phonenumbers.PhoneNumberFormat.E164
        )[1:]

        valSession = valSessionStore.getOrCreateTokenSession(
            medium='msisdn', address=msisdn, clientSecret=clientSecret
        )

        valSessionStore.setMtime(valSession.id, time_msec())

        if int(valSession.sendAttemptNumber) >= int(sendAttempt):
            logger.info("Not texting code because current send attempt (%d) is not less than given send attempt (%s)", int(sendAttempt), int(valSession.sendAttemptNumber))
            return valSession.id

        smsBodyTemplate = self.sydent.cfg.get('sms', 'bodyTemplate')
        originator = self.getOriginator(phoneNumber)

        logger.info(
github Twilio-org / rapid-response-kit / rapid_response_kit / utils / helpers.py View on Github external
return

    if raw_phone[0] == '+':
        # Phone number may already be in E.164 format.
        parse_type = None
    else:
        # If no country code information present, assume it's a US number
        parse_type = "US"

    try:
        phone_representation = phonenumbers.parse(raw_phone, parse_type)
    except phonenumbers.NumberParseException:
        return None

    return phonenumbers.format_number(phone_representation,
                                      phonenumbers.PhoneNumberFormat.E164)
github aparsons / bag-of-holding / project / boh / models.py View on Github external
def save(self, *args, **kwargs):
        if self.phone_work:
            self.phone_work = phonenumbers.format_number(phonenumbers.parse(self.phone_work, 'US'), phonenumbers.PhoneNumberFormat.E164)
        if self.phone_mobile:
            self.phone_mobile = phonenumbers.format_number(phonenumbers.parse(self.phone_mobile, 'US'), phonenumbers.PhoneNumberFormat.E164)
        self.email = self.email.lower()
        super(Person, self).save(*args, **kwargs)