本文整理汇总了Python中phonenumbers.parse方法的典型用法代码示例。如果您正苦于以下问题:Python phonenumbers.parse方法的具体用法?Python phonenumbers.parse怎么用?Python phonenumbers.parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类phonenumbers
的用法示例。
在下文中一共展示了phonenumbers.parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: clean
# 需要导入模块: import phonenumbers [as 别名]
# 或者: from phonenumbers import parse [as 别名]
def clean(self):
cd = super(CustomerForm, self).clean()
phone = cd.get('phone')
country = cd.get('country')
if len(phone) < 1:
return cd
try:
phonenumbers.parse(phone, country)
except phonenumbers.NumberParseException:
msg = _('Enter a valid phone number')
self._errors["phone"] = self.error_class([msg])
return cd
示例2: get_canonical_form
# 需要导入模块: import phonenumbers [as 别名]
# 或者: from phonenumbers import parse [as 别名]
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
示例3: normalize_phone
# 需要导入模块: import phonenumbers [as 别名]
# 或者: from phonenumbers import parse [as 别名]
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
示例4: validate_phone
# 需要导入模块: import phonenumbers [as 别名]
# 或者: from phonenumbers import parse [as 别名]
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
示例5: validate_new_password
# 需要导入模块: import phonenumbers [as 别名]
# 或者: from phonenumbers import parse [as 别名]
def validate_new_password(self, password):
user = self.context['request'].user
validate_password(password, user=user)
username = user.username
if len(username) and username.casefold() in password.casefold():
raise serializers.ValidationError(
_("The password is too similar to the username."))
phone = user.phone
if phone and phone_validator(phone):
phone = str(parse_phone(phone).national_number)
if phone in password:
raise serializers.ValidationError(
_("Passwords cannot contain your phone."))
return password
示例6: clean_phone
# 需要导入模块: import phonenumbers [as 别名]
# 或者: from phonenumbers import parse [as 别名]
def clean_phone(self):
phone = self.data.get('phone')
if phone:
if (phone != self.current_phone and
VerificationDevice.objects.filter(unverified_phone=phone
).exists()):
raise forms.ValidationError(
_("User with this Phone number already exists."))
try:
parse_phone(phone)
except NumberParseException:
raise forms.ValidationError(
_("Please enter a valid country code."))
else:
phone = None
return phone
示例7: clean_password
# 需要导入模块: import phonenumbers [as 别名]
# 或者: from phonenumbers import parse [as 别名]
def clean_password(self):
if not self.user or not self.user.update_profile:
raise forms.ValidationError(_("The password for this user can not "
"be changed."))
password = self.cleaned_data['password']
validate_password(password, user=self.user)
username = self.user.username
if len(username) and username.casefold() in password.casefold():
raise forms.ValidationError(
_("The password is too similar to the username."))
phone = self.user.phone
if phone and phone_validator(phone):
phone = str(parse_phone(phone).national_number)
if phone in password:
raise forms.ValidationError(
_("Passwords cannot contain your phone."))
return password
示例8: parse
# 需要导入模块: import phonenumbers [as 别名]
# 或者: from phonenumbers import parse [as 别名]
def parse(self, raw_value):
"""If the input is already a datetime,
pass it through. Otherwise, ensure that it is a str
and use dateutil to parse it
"""
value = self.empty_value
if raw_value is UNSET:
return value
if isinstance(raw_value, datetime) or raw_value is None:
return raw_value
self.assert_parse_received_correct_type(raw_value, str)
raw_value = self.parse_as_text(raw_value)
if raw_value:
try:
value = dateutil_parse(raw_value)
except ValueError:
self.add_error(
self.parse_error_message.format(raw_value))
else:
value = None
return value
示例9: __eq__
# 需要导入模块: import phonenumbers [as 别名]
# 或者: from phonenumbers import parse [as 别名]
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
示例10: __call__
# 需要导入模块: import phonenumbers [as 别名]
# 或者: from phonenumbers import parse [as 别名]
def __call__(self, node, value):
try:
phone = phonenumbers.parse(value)
except phonenumbers.NumberParseException:
raise colander.Invalid(
node,
_(
u"Phone must be in format +XXXXXXXXXXX "
u"and contains country code",
mapping={'val': value}
)
)
if not phonenumbers.is_valid_number(phone):
raise colander.Invalid(
node,
_(
u"Phone is not valid",
mapping={'val': value}
)
)
示例11: format
# 需要导入模块: import phonenumbers [as 别名]
# 或者: from phonenumbers import parse [as 别名]
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
示例12: default_get
# 需要导入模块: import phonenumbers [as 别名]
# 或者: from phonenumbers import parse [as 别名]
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
示例13: create_partner
# 需要导入模块: import phonenumbers [as 别名]
# 或者: from phonenumbers import parse [as 别名]
def create_partner(self, cr, uid, ids, context=None):
'''Function called by the related button of the wizard'''
if context is None:
context = {}
wiz = self.browse(cr, uid, ids[0], context=context)
parsed_num = phonenumbers.parse(wiz.e164_number, None)
number_type = phonenumbers.number_type(parsed_num)
context['default_%s' % wiz.number_type] = wiz.e164_number
action = {
'name': _('Create New Partner'),
'view_mode': 'form,tree,kanban',
'res_model': 'res.partner',
'type': 'ir.actions.act_window',
'nodestroy': False,
'target': 'current',
'context': context,
}
return action
示例14: geolocate_phone_number
# 需要导入模块: import phonenumbers [as 别名]
# 或者: from phonenumbers import parse [as 别名]
def geolocate_phone_number(number, my_country_code, lang):
import phonenumbers
from phonenumbers import geocoder
res = ''
phonenum = phonenumbers.parse(number, my_country_code.upper())
city = phonenumbers.geocoder.description_for_number(phonenum, lang.lower())
country_code = phonenumbers.region_code_for_number(phonenum)
# We don't display the country name when it's my own country
if country_code == my_country_code.upper():
if city:
res = city
else:
# Convert country code to country name
country = phonenumbers.geocoder._region_display_name(
country_code, lang.lower())
if country and city:
res = country + ' ' + city
elif country and not city:
res = country
return res
示例15: _parse_phone_number
# 需要导入模块: import phonenumbers [as 别名]
# 或者: from phonenumbers import parse [as 别名]
def _parse_phone_number(cls, phone_number_string):
"""
Parses a phone number string and raises proper exceptions in case it is invalid
Args:
phone_number_string (str): a string representing a phone number
Returns:
phonenumbers.phonenumber.PhoneNumber: a PhoneNumber object
"""
try:
phone_number = phonenumbers.parse(phone_number_string)
except phonenumbers.phonenumberutil.NumberParseException:
raise InvalidProfileDataException('Stored phone number is in an invalid string')
if not phonenumbers.is_valid_number(phone_number):
raise InvalidProfileDataException('Stored phone number is in an invalid phone number')
return phone_number