Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
if not phonenumbers.is_possible_number(smsnumber_obj):
errormessage = u'SMS Number is not possibly valid: {}.'.format(smsnumber)
log.logger.error(errormessage)
raise UserWarning(errormessage)
except phonenumbers.NumberParseException as e:
errormessage = u'SMS Unable to parse number {}. Error: {}'.format(smsnumber, e.message)
log.logger.error(errormessage)
raise UserWarning(errormessage)
if not phonenumbers.is_valid_number(smsnumber_obj):
errormessage = u'SMS Number is not valid: {}.'.format(smsnumber)
log.logger.error(errormessage)
raise UserWarning(errormessage)
e164_number = phonenumbers.format_number(smsnumber_obj, phonenumbers.PhoneNumberFormat.E164)
if not e164_number:
errormessage = u'SMS number {} could not be converted to E.164 for an unknown reason.'.format(smsnumber)
log.logger.error(errormessage)
raise UserWarning(errormessage)
# all good, return it!
return e164_number
except Exception as e:
log.logger.error(e.message)
return None
:param country_phone_code: country dial in codes, defined by the ITU-T (Ex: 32 for Belgium)
:type country_phone_code: int
:rtype: str
"""
try:
phone_nbr = phone_parse(number, country_code)
except (phonenumbers.phonenumberutil.NumberParseException, UserError) as e:
if raise_exception:
raise
else:
_logger.warning(_('Unable to format %s:\n%s'), number, e)
return number
if always_international or phone_nbr.country_code != country_phone_code:
phone_fmt = phonenumbers.PhoneNumberFormat.INTERNATIONAL
else:
phone_fmt = phonenumbers.PhoneNumberFormat.NATIONAL
return phonenumbers.format_number(phone_nbr, phone_fmt)
except ValueError:
self.valid = False
class EmailResult(Result):
category = ExtractedEntity.EMAIL
def __init__(self, ctx, label, start, end):
super(EmailResult, self).__init__(ctx, label, start, end)
self.key = self.label_key(self.label)
self.valid = self.key is not None
# TODO: do we want to do TLD -> country?
class PhoneResult(Result):
FORMAT = phonenumbers.PhoneNumberFormat.E164
category = ExtractedEntity.PHONE
def __init__(self, ctx, label, start, end):
super(PhoneResult, self).__init__(ctx, label, start, end)
number = self._parse(label)
for country in ctx.countries:
if number is None:
number = self._parse(label, country)
self.valid = number is not None
if number is not None:
self.countries = [geocoder.region_code_for_number(number)]
self.label = phonenumbers.format_number(number, self.FORMAT)
self.key = self.label
def _parse(self, number, region=None):
try:
#!/usr/bin/env python
# encoding: utf-8
import phonenumbers
from .simple import StringField
class PhoneNumber(phonenumbers.phonenumber.PhoneNumber):
'''
extend phonenumbers.phonenumber.PhoneNumber with easier accessors
'''
FORMATS = {
'E164': phonenumbers.PhoneNumberFormat.E164,
'INTERNATIONAL': phonenumbers.PhoneNumberFormat.INTERNATIONAL,
'NATIONAL': phonenumbers.PhoneNumberFormat.NATIONAL,
'RFC3966': phonenumbers.PhoneNumberFormat.RFC3966,
}
default_format = 'INTERNATIONAL'
_region = ''
def __repr__(self):
fmt = self.FORMATS[self.default_format]
return '<{} {}>'.format(self.__class__.__name__, self.format_as(fmt))
@classmethod
def from_string(cls, phone_number, region=None):
try:
phone_number_obj = cls()
phonenumbers.parse(number=phone_number, region=region,
'current_episode_type': episode.get_case_property('episode_type'),
'alcohol_history': episode.get_case_property('alcohol_history'),
'alcohol_deaddiction': episode.get_case_property('alcohol_deaddiction'),
'tobacco_user': episode.get_case_property('tobacco_user'),
'occupation': episode.get_case_property('occupation'),
'phone_number_other': episode.get_case_property('phone_number_other'),
})
phone_number = person.get_case_property('phone_number')
if phone_number:
number = phonenumbers.parse(phone_number, "IN")
number.italian_leading_zero = False
props['contact_phone_number'] = strip_plus(
phonenumbers.format_number(
number,
phonenumbers.PhoneNumberFormat.E164)
)
location = self.locations.get(person.owner_id)
if location:
dataset = 'real' if location.metadata.get('is_test') == 'no' else 'test'
props['dataset'] = person.get_case_property('dataset') or dataset
if location.location_type.code == 'phi':
props['phi_name'] = location.name
ancestors_by_type = self.get_ancestors_by_type(location)
if 'tu' in ancestors_by_type:
props['tu_name'] = ancestors_by_type['tu'].name
props['tu_id'] = ancestors_by_type['tu'].location_id
if 'dto' in ancestors_by_type:
props['dto_name'] = ancestors_by_type['dto'].name
props['dto_id'] = ancestors_by_type['dto'].location_id
import re
import urlnorm
import parsedatetime
import countrynames
import phonenumbers
from normality import stringify
from urlparse import urlparse
from datetime import date, datetime
from urlparse import urldefrag
from phonenumbers.phonenumberutil import NumberParseException
from flanker.addresslib import address
from aleph.data.validate import is_country_code, is_domain, is_partial_date
PHONE_FORMAT = phonenumbers.PhoneNumberFormat.INTERNATIONAL
CUT_ZEROES = re.compile(r'(\-00?)?\-00?$')
def parse_phone(number, country=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
"""
number = stringify(number)
if number is None:
return
if country is not None:
def to_raw_phone(cls, value, region=None):
if isinstance(value, basestring) and value != '':
try:
number = value
phone = PhoneField._parse(number, region)
number = phonenumbers.format_number(
phone, phonenumbers.PhoneNumberFormat.E164
)
if phone.extension:
number += 'x%s' % phone.extension
return number
except phonenumbers.NumberParseException:
pass
return value
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(
settings, 'PHONENUMBER_DEFAULT_FORMAT', 'INTERNATIONAL')
fmt = self.format_map[format_string]