Python phonenumbers.format_number() Examples
The following are 30
code examples of phonenumbers.format_number().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
phonenumbers
, or try the search function
.
Example #1
Source File: phone_util.py From flask-security with MIT License | 7 votes |
def get_canonical_form(self, input_data): """ Validate and return a canonical form to be stored in DB and compared against. Returns ``None`` if input isn't a valid phone number. """ import phonenumbers try: z = phonenumbers.parse( input_data, region=config_value("PHONE_REGION_DEFAULT") ) if phonenumbers.is_valid_number(z): return phonenumbers.format_number( z, phonenumbers.PhoneNumberFormat.E164 ) return None except phonenumbers.phonenumberutil.NumberParseException: return None
Example #2
Source File: models.py From casepro with BSD 3-Clause "New" or "Revised" License | 7 votes |
def validate_phone(cls, number): """ Validates the given phone number which should be in E164 format. """ try: parsed = phonenumbers.parse(number) except phonenumbers.NumberParseException as e: raise InvalidURN(str(e)) if number != phonenumbers.format_number(parsed, phonenumbers.PhoneNumberFormat.E164): raise InvalidURN("Phone numbers must be in E164 format") if not phonenumbers.is_possible_number(parsed) or not phonenumbers.is_valid_number(parsed): raise InvalidURN("Phone numbers must be in E164 format") return True
Example #3
Source File: functions.py From docassemble with MIT License | 6 votes |
def phone_number_part(number, part, country=None): ensure_definition(number, part, country) if country is None: country = get_country() if isinstance(number, str): m = re.search(r'^whatsapp:(.*)', number) if m: number = m.group(1) try: pn = phonenumbers.parse(number, country) except: return '' formatted_number = phonenumbers.format_number(pn, phonenumbers.PhoneNumberFormat.NATIONAL) parts = [x for x in re.split(r'[^0-9]+', formatted_number) if re.search(r'[0-9]', x)] if part < len(parts): return parts[part] else: return ''
Example #4
Source File: utils.py From flask-shop with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __eq__(self, other): """ Override parent equality because we store only string representation of phone number, so we must compare only this string representation """ if ( isinstance(other, PhoneNumber) or isinstance(other, phonenumbers.PhoneNumber) or isinstance(other, str) ): format_string = "E164" default_region = None fmt = self.format_map[format_string] if isinstance(other, str): # convert string to phonenumbers.PhoneNumber # instance try: other = phonenumbers.parse(other, region=default_region) except phonenumbers.NumberParseException: # Conversion is not possible, thus not equal return False other_string = phonenumbers.format_number(other, fmt) return self.format_as(fmt) == other_string else: return False
Example #5
Source File: report_sxw_format.py From openerp-freeswitch-connector with GNU Affero General Public License v3.0 | 6 votes |
def format( self, text, oldtag=None, phone=False, phone_format='international'): if self.pool.get('base.phone.installed') and phone and text: # text should already be in E164 format, so we don't have # to give a country code to phonenumbers.parse() phone_number = phonenumbers.parse(text) if phone_format == 'international': res = phonenumbers.format_number( phone_number, phonenumbers.PhoneNumberFormat.INTERNATIONAL) elif phone_format == 'national': res = phonenumbers.format_number( phone_number, phonenumbers.PhoneNumberFormat.NATIONAL) elif phone_format == 'e164': res = phonenumbers.format_number( phone_number, phonenumbers.PhoneNumberFormat.E164) else: res = text else: res = format_original(self, text, oldtag=oldtag) return res
Example #6
Source File: number_not_found.py From openerp-freeswitch-connector with GNU Affero General Public License v3.0 | 6 votes |
def default_get(self, cr, uid, fields_list, context=None): res = super(number_not_found, self).default_get( cr, uid, fields_list, context=context) if not res: res = {} if res.get('calling_number'): convert = self.pool['phone.common']._generic_reformat_phonenumbers( cr, uid, {'phone': res.get('calling_number')}, context=context) parsed_num = phonenumbers.parse(convert.get('phone')) res['e164_number'] = phonenumbers.format_number( parsed_num, phonenumbers.PhoneNumberFormat.INTERNATIONAL) number_type = phonenumbers.number_type(parsed_num) if number_type == 1: res['number_type'] = 'mobile' else: res['number_type'] = 'phone' return res
Example #7
Source File: widgets.py From esdc-ce with Apache License 2.0 | 6 votes |
def clean_international_phonenumber(value): """ Validate phone number taken from TelPrefixInput and return in format suitable for our DB. """ invalid_number_message = _(u'The phone number entered is not valid.') try: num = phonenumbers.parse(value) if not phonenumbers.is_valid_number(num): raise forms.ValidationError(invalid_number_message) except phonenumbers.NumberParseException: raise forms.ValidationError(invalid_number_message) return phonenumbers.format_number(num, phonenumbers.PhoneNumberFormat.E164) # noinspection PyAbstractClass
Example #8
Source File: functions.py From docassemble with MIT License | 6 votes |
def phone_number_in_e164(number, country=None): """Given a phone number and a country code, returns the number in E.164 format. Returns None if the number could not be so formatted.""" ensure_definition(number, country) if country is None: country = get_country() use_whatsapp = False if isinstance(number, str): m = re.search(r'^whatsapp:(.*)', number) if m: number = m.group(1) use_whatsapp = True try: pn = phonenumbers.parse(number, country) output = phonenumbers.format_number(pn, phonenumbers.PhoneNumberFormat.E164) except: return None if use_whatsapp: return 'whatsapp:' + output return output
Example #9
Source File: functions.py From docassemble with MIT License | 6 votes |
def phone_number_formatted(number, country=None): """Given a phone number and a country code, returns the number in the standard format for the country. Returns None if the number could not be so formatted.""" ensure_definition(number, country) if country is None: country = get_country() if isinstance(number, str): m = re.search(r'^whatsapp:(.*)', number) if m: number = m.group(1) try: pn = phonenumbers.parse(number, country) output = phonenumbers.format_number(pn, phonenumbers.PhoneNumberFormat.NATIONAL) except: return None return output
Example #10
Source File: models.py From casepro with BSD 3-Clause "New" or "Revised" License | 6 votes |
def normalize_phone(cls, number): """ Normalizes the passed in phone number """ # remove any invalid characters number = regex.sub(r"[^0-9a-z\+]", "", number.lower(), regex.V0) # add on a plus if it looks like it could be a fully qualified number if len(number) >= 11 and number[0] not in ["+", "0"]: number = "+" + number try: normalized = phonenumbers.parse(number) if phonenumbers.is_possible_number(normalized): return phonenumbers.format_number(normalized, phonenumbers.PhoneNumberFormat.E164) except Exception: pass return number
Example #11
Source File: models.py From jorvik with GNU General Public License v3.0 | 6 votes |
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
Example #12
Source File: util.py From docassemble with MIT License | 5 votes |
def phone_string(person, country=None): if person is None: return None phone_number = None if isinstance(person, Person): phone_number = person.sms_number() elif isinstance(person, phonenumbers.PhoneNumber): phone_number = phonenumbers.format_number(person, phonenumbers.PhoneNumberFormat.E164) else: phone_number = phone_number_in_e164(person, country=country) return phone_number
Example #13
Source File: util.py From docassemble with MIT License | 5 votes |
def fax_string(person, country=None): if person is None: return None fax_number = None if isinstance(person, Person): fax_number = person.facsimile_number(country=country) elif isinstance(person, phonenumbers.PhoneNumber): fax_number = phonenumbers.format_number(person, phonenumbers.PhoneNumberFormat.E164) else: fax_number = phone_number_in_e164(person, country=country) return fax_number
Example #14
Source File: customer.py From Servo with BSD 2-Clause "Simplified" License | 5 votes |
def get_international_phone(self): n = self.get_phone() fmt = phonenumbers.PhoneNumberFormat.INTERNATIONAL return phonenumbers.format_number(n, fmt)
Example #15
Source File: misc_tags.py From mitoc-trips with GNU General Public License v3.0 | 5 votes |
def format_phone_number(number): """ Format phone numbers with spacing & area code. """ if not number: return '' # Only include country code if outside the US if number.country_code == 1: fmt = phonenumbers.PhoneNumberFormat.NATIONAL else: fmt = phonenumbers.PhoneNumberFormat.INTERNATIONAL return phonenumbers.format_number(number, fmt)
Example #16
Source File: address.py From correios with Apache License 2.0 | 5 votes |
def display(self) -> str: if not self.parsed: return "" country_code = "+{!s}".format(self.parsed.country_code) return format_number(self.parsed, PhoneNumberFormat.INTERNATIONAL).replace(country_code, "").strip()
Example #17
Source File: models.py From jorvik with GNU General Public License v3.0 | 5 votes |
def nazionale(self): """ Ritorna il numero formattato come numero nazionale. :return: Stringa che rappresenta il numero in formato nazionale. """ return phonenumbers.format_number(self._phonenumber(), phonenumbers.PhoneNumberFormat.NATIONAL)
Example #18
Source File: base_phone.py From openerp-freeswitch-connector with GNU Affero General Public License v3.0 | 5 votes |
def _generic_reformat_phonenumbers( self, cr, uid, vals, phonefields=[ 'phone', 'partner_phone', 'work_phone', 'fax', 'mobile', 'partner_mobile', 'mobile_phone', ], context=None): """Reformat phone numbers in E.164 format i.e. +33141981242""" if any([vals.get(field) for field in phonefields]): user = self.pool['res.users'].browse(cr, uid, uid, context=context) # country_id on res.company is a fields.function that looks at # company_id.partner_id.addres(default).country_id if user.company_id.country_id: user_countrycode = user.company_id.country_id.code else: # We need to raise an exception here because, if we pass None # as second arg of phonenumbers.parse(), it will raise an # exception when you try to enter a phone number in # national format... so it's better to raise the exception here raise orm.except_orm( _('Error:'), _("You should set a country on the company '%s'") % user.company_id.name) for field in phonefields: if vals.get(field): init_value = vals.get(field) try: res_parse = phonenumbers.parse( vals.get(field), user_countrycode) except Exception, e: raise orm.except_orm( _('Error:'), _("Cannot reformat the phone number '%s' to " "international format. Error message: %s") % (vals.get(field), e)) vals[field] = phonenumbers.format_number( res_parse, phonenumbers.PhoneNumberFormat.E164) if init_value != vals[field]: _logger.info( "%s initial value: '%s' updated value: '%s'" % (field, init_value, vals[field]))
Example #19
Source File: base_phone.py From openerp-freeswitch-connector with GNU Affero General Public License v3.0 | 5 votes |
def generic_phonenumber_to_e164( self, cr, uid, ids, field_from_to_seq, context=None): result = {} from_field_seq = [item[0] for item in field_from_to_seq] for record in self.read(cr, uid, ids, from_field_seq, context=context): result[record['id']] = {} for fromfield, tofield in field_from_to_seq: if not record.get(fromfield): res = False else: try: res = phonenumbers.format_number( phonenumbers.parse(record.get(fromfield), None), phonenumbers.PhoneNumberFormat.E164) except Exception, e: _logger.error( "Cannot reformat the phone number '%s' to E.164 " "format. Error message: %s" % (record.get(fromfield), e)) _logger.error( "You should fix this number and run the wizard " "'Reformat all phone numbers' from the menu " "Settings > Configuration > Phones") # If I raise an exception here, it won't be possible to # install the module on a DB with bad phone numbers res = False result[record['id']][tofield] = res
Example #20
Source File: models.py From jorvik with GNU General Public License v3.0 | 5 votes |
def internazionale(self): """ Ritorna il numero formattato come numero internazionale. :return: Stringa che rappresenta il numero in formato internazionale. """ return phonenumbers.format_number(self._phonenumber(), phonenumbers.PhoneNumberFormat.INTERNATIONAL)
Example #21
Source File: ldap_sync.py From oncall with BSD 2-Clause "Simplified" License | 5 votes |
def normalize_phone_number(num): return format_number(parse(num.decode('utf-8'), 'US'), PhoneNumberFormat.INTERNATIONAL)
Example #22
Source File: slack.py From oncall with BSD 2-Clause "Simplified" License | 5 votes |
def normalize_phone_number(num): return format_number(parse(num.decode('utf-8'), 'US'), PhoneNumberFormat.INTERNATIONAL)
Example #23
Source File: htk_tags.py From django-htk with MIT License | 5 votes |
def phonenumber(value, country='US'): """Formats a phone number for a country """ import phonenumbers try: formatted = phonenumbers.format_number(phonenumbers.parse(value, country), phonenumbers.PhoneNumberFormat.NATIONAL) except: formatted = value return formatted
Example #24
Source File: models.py From jorvik with GNU General Public License v3.0 | 5 votes |
def e164(self): """ Ritorna il numero formattato come numero internazionale E.164. :return: Stringa che rappresenta il numero in formato internazionale E.164. """ return phonenumbers.format_number(self._phonenumber(), phonenumbers.PhoneNumberFormat.E164)
Example #25
Source File: phoneinfoga.py From Phoneinfoga with GNU General Public License v3.0 | 5 votes |
def localScan(InputNumber): global number global localNumber global internationalNumber global numberCountryCode global numberCountry print(code_info + 'Running local scan...') FormattedPhoneNumber = "+" + formatNumber(InputNumber) try: PhoneNumberObject = phonenumbers.parse(FormattedPhoneNumber, None) except: return False else: if not phonenumbers.is_valid_number(PhoneNumberObject): return False number = phonenumbers.format_number(PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace('+', '') numberCountryCode = phonenumbers.format_number(PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(' ')[0] countryRequest = json.loads(requests.request('GET', 'https://restcountries.eu/rest/v2/callingcode/{}'.format(numberCountryCode.replace('+', ''))).content) numberCountry = countryRequest[0]['alpha2Code'] localNumber = phonenumbers.format_number(PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace(numberCountryCode, '') internationalNumber = phonenumbers.format_number(PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL) print(code_result + 'International format: {}'.format(internationalNumber)) print(code_result + 'Local format: 0{}'.format(localNumber)) print(code_result + 'Country code: {}'.format(numberCountryCode)) print(code_result + 'Location: {}'.format(geocoder.description_for_number(PhoneNumberObject, "en"))) print(code_result + 'Carrier: {}'.format(carrier.name_for_number(PhoneNumberObject, 'en'))) print(code_result + 'Area: {}'.format(geocoder.description_for_number(PhoneNumberObject, 'en'))) for timezoneResult in timezone.time_zones_for_number(PhoneNumberObject): print(code_result + 'Timezone: {}'.format(timezoneResult)) if phonenumbers.is_possible_number(PhoneNumberObject): print(code_info + 'The number is valid and possible.') else: print(code_warning + 'The number is valid but might not be possible.')
Example #26
Source File: customer.py From Servo with BSD 2-Clause "Simplified" License | 5 votes |
def get_standard_phone(self): n = self.get_phone() fmt = phonenumbers.PhoneNumberFormat.E164 return phonenumbers.format_number(n, fmt)
Example #27
Source File: customer.py From Servo with BSD 2-Clause "Simplified" License | 5 votes |
def get_national_phone(self): n = self.get_phone() fmt = phonenumbers.PhoneNumberFormat.NATIONAL return phonenumbers.format_number(n, fmt)
Example #28
Source File: phone_number_filter.py From call-tracking-django with MIT License | 5 votes |
def national_format(value): """Displays a phone number in an appropriate national format""" # Since this is a template filter, we will just pass through # the original value if we encounter any error try: number = phonenumbers.parse(value) formatted_number = phonenumbers.format_number( number, phonenumbers.PhoneNumberFormat.NATIONAL) except Exception: return value return formatted_number
Example #29
Source File: phone.py From SempoBlockchain with GNU General Public License v3.0 | 5 votes |
def proccess_phone_number(phone_number, region=None, ignore_region=False): """ Parse any given phone number. :param phone_number: int :param region: ISO 3166-1 alpha-2 codes :param ignore_region: Boolean. True returns original phone :return: """ from server.models.organisation import Organisation if phone_number is None: return None if ignore_region: return phone_number if region is None: try: region = g.active_organisation.country_code except AttributeError: region = Organisation.master_organisation().country_code if not isinstance(phone_number, str): try: phone_number = str(int(phone_number)) except ValueError: pass phone_number_object = phonenumbers.parse(phone_number, region) parsed_phone_number = phonenumbers.format_number(phone_number_object, phonenumbers.PhoneNumberFormat.E164) return parsed_phone_number
Example #30
Source File: utils.py From idunn with Apache License 2.0 | 5 votes |
def get_formatted_phone_number(phone, output_format): try: if not isinstance(phone, phonenumbers.phonenumber.PhoneNumber): phone = phonenumbers.parse(phone) return phonenumbers.format_number(phone, output_format) except Exception as e: logger.warning("failed to format phone number: {}".format(e), exc_info=True) return None