Beispiel #1
0
def parse_phone(phone_str, country_code=0, alpha2=u"US"):
    "returns a dict with phone number properties if the string is parsable"
    """
        returns dict w/: phone_str, phone_str_digits_only, country_code, region, errors (if any)
    """
    try:
        if COUNTRY_RG.match(phone_str):
            phone = parse_number(rm_punct_leaving_plus_sign(phone_str), keep_raw_input=True)
        elif country_code != 0:
            phone = parse_number(u"+{} {}".format(country_code, phone_str), keep_raw_input=True)
        else:
            country_code = country_code_for_region(alpha2)
            if country_code != 0:
                phone = parse_number(u"+{} {}".format(country_code, phone_str), keep_raw_input=True)
            else:
                phone = parse_number(phone_str, alpha2, keep_raw_input=True)
        phone_dict = phone.__dict__.copy()
        phone_dict['region_code'] = region_code_for_country_code(phone.country_code)
        phone_dict['phone_str'] = phone_str
        phone_dict['is_valid_for_region'] = is_valid_number_for_region(phone, region_code_for_country_code(phone.country_code))
    except:
        keys = ['region_code','italian_leading_zero','extension','national_number','is_valid_for_region','raw_input','country_code_source','phone_str','country_code','number_of_leading_zeros','preferred_domestic_carrier_code']
        phone_dict = {k: None for k in keys}
        phone_dict['phone_str'] = phone_str
    return phone_dict
 def get_mobile(self, obj):
     try:
         p = parse_number(obj.mobile,
                          settings.CAMPUSONLINE_PHONE_NUMBER_REGION)
         return format_number(p, PhoneNumberFormat.INTERNATIONAL)
     except phonenumberutil.NumberParseException:
         return None
Beispiel #3
0
def validate_number(number,
                    country,
                    include_description=True) -> Optional[Number]:
    try:
        p = parse_number(number, country)
    except NumberParseException:
        return

    if not is_valid_number(p):
        return

    is_mobile = number_type(p) in MOBILE_NUMBER_TYPES
    descr = None
    if include_description:
        country = country_name_for_number(p, 'en')
        region = description_for_number(p, 'en')
        descr = country if country == region else f'{region}, {country}'

    return Number(
        number=format_number(p, PhoneNumberFormat.E164),
        country_code=f'{p.country_code}',
        number_formatted=format_number(p, PhoneNumberFormat.INTERNATIONAL),
        descr=descr,
        is_mobile=is_mobile,
    )
Beispiel #4
0
 def country_hint(self, value):
     try:
         number = parse_number(value)
         code = geocoder.region_code_for_number(number)
         if code is not None:
             return code.lower()
     except NumberParseException:
         return None
Beispiel #5
0
 def country_hint(self, value: str) -> Optional[str]:
     try:
         number = parse_number(value)
         code = geocoder.region_code_for_number(number)
         if code is None:
             return None
         return str(code).lower()
     except NumberParseException:
         return None
Beispiel #6
0
def prepare_number(number, country=None):
    if not country:
        country = locale.getlocale()[0].split("_")[1]

    try:
        number = parse_number(number, country)
    except NumberParseException:
        return ''

    return format_number(number, PhoneNumberFormat.E164)
Beispiel #7
0
    def _deserialize(self, value, attr, data):
        value = value.replace(" ", "")

        try:
            value = parse_number(value, "FR")

        except NumberParseException:
            raise self.fail("invalid")

        return f"+{value.country_code}{value.national_number}"
Beispiel #8
0
def prepare_number(number, country = None):
    if not country:
        country = locale.getlocale()[0].split("_")[1]

    try:
      number = parse_number(number, country)
    except NumberParseException:
        return ''

    return format_number(number, PhoneNumberFormat.E164)
Beispiel #9
0
    def _parse_number(self, number, proxy=None):
        """Parse a phone number and return in international format.

        If no valid phone number can be detected, None is returned. If
        a country code is supplied, this will be used to infer the
        prefix.

        https://github.com/daviddrysdale/python-phonenumbers
        """
        for code in self._clean_countries(proxy):
            try:
                yield parse_number(number, code)
            except NumberParseException:
                pass
Beispiel #10
0
    def clean_text(self, number, countries=None, country=None, **kwargs):
        """Parse a phone number and return in international format.

        If no valid phone number can be detected, None is returned. If
        a country code is supplied, this will be used to infer the
        prefix.

        https://github.com/daviddrysdale/python-phonenumbers
        """
        for code in self._clean_countries(countries, country):
            try:
                num = parse_number(number, code)
                if is_possible_number(num):
                    if is_valid_number(num):
                        return format_number(num, PhoneNumberFormat.E164)
            except NumberParseException:
                pass
    def attempt_creation(self):
        """Validate fields and attempt to create account"""
        self.create_account_button.disabled = True

        # list of all problems with user input
        errors = []

        # the following series of conditionals are all for validating
        # user input before we attempt to insert it into the database

        if not self.username_field.text:
            errors.append('username is required')

        # neither of these should be possible (field is filtered),
        # but just in case
        elif len(self.username_field.text) > 32:
            errors.append('username maximum length is 32 characters')
        elif re.search(r'\W', self.username_field.text):
            errors.append(
                'username can only contain letters, numbers, and underscores')

        if not self.password_field.text:
            errors.append('password is required')
        elif len(self.password_field.text) < 8:
            errors.append('password minimum length is 8 characters')

        if not self.phone_field.text:
            errors.append('phone number is required')
        else:
            try:
                phone = parse_number(self.phone_field.text, 'US')
            except NumberParseException:
                valid = False
            else:
                valid = is_valid_number(phone)

            if not valid:
                errors.append(
                    f'"{self.phone_field.text}" is not a valid US phone number'
                )

        # if all inputs are valid, attempt to create a new account
        if not errors:
            try:
                create_user(self.username_field.text, self.password_field.text,
                            format_number(phone, 'NATIONAL'))
            except AccountError as e:
                # username already exists
                errors.append(e.message)
            else:
                # account created successfully
                AlertPopup(title='Success',
                           label=f'User "{self.username_field.text}" '
                           'has been created',
                           button='Go to Login',
                           on_dismiss=self.switch_to_login).open()
                return

        # display input errors to the user
        popup = AlertPopup(title='Errors',
                           label='\n'.join(f'\u2022 {e}' for e in errors),
                           button='Dismiss')
        popup.label.halign = 'left'
        popup.open()

        self.create_account_button.disabled = False
Beispiel #12
0
 def caption(self, value: str) -> str:
     number = parse_number(value)
     formatted = format_number(number, PhoneNumberFormat.INTERNATIONAL)
     return str(formatted)
Beispiel #13
0
 def caption(self, value):
     number = parse_number(value)
     return format_number(number, PhoneNumberFormat.INTERNATIONAL)
Beispiel #14
0
 def country_hint(self, value):
     try:
         number = parse_number(value)
         return geocoder.region_code_for_number(number).lower()
     except NumberParseException:
         pass