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 country(code): code = phonenumbers.region_code_for_country_code(code) print(code) if code == "ZZ": return jsonify({"message": "Resource not found"}), 404 return jsonify( {"country": country_converter.convert(code, to="short_name")})
def localScan(InputNumber, print_results=True): print("Running local scan...") FormattedPhoneNumber = "+" + formatNumber(InputNumber) try: PhoneNumberObject = phonenumbers.parse(FormattedPhoneNumber, None) except Exception as e: print(e) 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] numberCountry = phonenumbers.region_code_for_country_code( int(numberCountryCode) ) localNumber = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164 ).replace(numberCountryCode, "") internationalNumber = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL ) country = geocoder.country_name_for_number(PhoneNumberObject, "en") location = geocoder.description_for_number(PhoneNumberObject, "en") carrierName = carrier.name_for_number(PhoneNumberObject, "en") if print_results: print("International format: {}".format(internationalNumber)) print("Local format: {}".format(localNumber)) print("Country found: {} ({})".format(country, numberCountryCode)) print("City/Area: {}".format(location)) print("Carrier: {}".format(carrierName)) for timezoneResult in timezone.time_zones_for_number(PhoneNumberObject): print("Timezone: {}".format(timezoneResult)) if phonenumbers.is_possible_number(PhoneNumberObject): print("The number is valid and possible.") else: print("The number is valid but might not be possible.") numberObj = {} numberObj["input"] = InputNumber numberObj["default"] = number numberObj["local"] = localNumber numberObj["international"] = internationalNumber numberObj["country"] = country numberObj["countryCode"] = numberCountryCode numberObj["countryIsoCode"] = numberCountry numberObj["location"] = location numberObj["carrier"] = carrierName return numberObj
def numberScan(): global phoneNumberGET, phoneNumber, numberNSCAN, numberCC, numberC, numberLOCAL, numberINTER, countryNSCAN, locationNSCAN, carrierNameNSCAN phoneNumberGET = numberSCANentryVar.get() #GET INFORMATIONS - PHONE NUMBER SCANNER FRAME phoneNumber = phonenumbers.parse(phoneNumberGET, None) numberNSCAN = phonenumbers.format_number( phoneNumber, phonenumbers.PhoneNumberFormat.E164).replace('+', '') numberCC = phonenumbers.format_number( phoneNumber, phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(' ')[0] numberC = phonenumbers.region_code_for_country_code(int(numberCC)) numberLOCAL = phonenumbers.format_number( phoneNumber, phonenumbers.PhoneNumberFormat.E164).replace(numberCC, '') numberINTER = phonenumbers.format_number( phoneNumber, phonenumbers.PhoneNumberFormat.INTERNATIONAL) countryNSCAN = geocoder.country_name_for_number(phoneNumber, 'en') locationNSCAN = geocoder.description_for_number(phoneNumber, 'en') carrierNameNSCAN = carrier.name_for_number(phoneNumber, 'en') #APPLY RESULTS - PHONE NUMBER SCANNER FRAME numberReset() numberSCANentryVar.set(phoneNumberGET) localNSCANentryVar.set(numberLOCAL) interNSCANentryVar.set(numberINTER) countryNSCANentryVar.set("{} ({})".format(countryNSCAN, numberCC)) areaNSCANentryVar.set(locationNSCAN) carrierNSCANentryVar.set(carrierNameNSCAN) for timezoneResult in timezone.time_zones_for_number(phoneNumber): timezoneNSCANentryVar.set(timezoneResult) if phonenumbers.is_possible_number(phoneNumber): validNSCANentryVar.set("VALID+POSSIBLE") else: validNSCANentryVar.set("INVALID")
def validate_phonenumber(self, field): data = field.data print("DATA: ", data) if not data: # Don't validate if nothing was provided return field try: if not data.startswith('+'): # Maybe they forgot this? data = '+' + data parsed = phonenumbers.parse(data) except: flash( "Please ensure you prefix the phone number with your country code." ) raise ValidationError("This is not a valid phone number") user = User.query.filter_by(phonenumber=data).first() if user and user.id != self.user.id: raise ValidationError("Phone number already on record.") if not phonenumbers.is_valid_number(parsed): flash( "Please ensure you prefix the phone number with your country code." ) raise ValidationError("This is not a valid phone number") if not carrier._is_mobile(phonenumberutil.number_type(parsed)): raise ValidationError( "This phone number doesn't look like a mobile phone number") self.phonenumber_locale = phonenumbers.region_code_for_country_code( parsed.country_code)
def format_phonenumber(number, international=True): # type: (Text, bool) -> Text """Format phone number for display. No formatting is applied if the number is not a valid phonenumber. :param number: the phone number to format. :param international: always use international format, unless number is in national format OR country is the same as app's default country. """ country = default_country() or "FR" try: pn = phonenumbers.parse(number, country) except phonenumbers.NumberParseException: return number except BaseException: logger.exception( 'error while applying jinja filter "phonenumber" ' "- filter ignored" ) return number if not (phonenumbers.is_possible_number(pn) and phonenumbers.is_valid_number(pn)): return number fmt = phonenumbers.PhoneNumberFormat.INTERNATIONAL number_country = phonenumbers.region_code_for_country_code(pn.country_code) if not international and number_country == country: fmt = phonenumbers.PhoneNumberFormat.NATIONAL return phonenumbers.format_number(pn, fmt)
def validate_phone_number(value, validation_error_class): """ :type value:fields.PhoneNumber :return: """ assert type(value) is PhoneNumber, "%s instance was supplied instead of PhoneNumber " % (type(value),) try: value.region_code = phonenumbers.region_code_for_country_code(int(value.country_code)) value.google_phone_number = phonenumbers.parse(value.phone_number, value.region_code) value.country_code = value.google_phone_number.country_code if not phonenumbers.is_valid_number(value.google_phone_number): fixed = phonenumbers.format_number(phonenumbers.example_number_for_type( value.region_code, PhoneNumberType.FIXED_LINE ), phonenumbers.PhoneNumberFormat.NATIONAL) mobile = phonenumbers.format_number(phonenumbers.example_number_for_type( value.region_code, PhoneNumberType.MOBILE ), phonenumbers.PhoneNumberFormat.NATIONAL) raise validation_error_class( 'Invalid number. format example are: ' + 'for fixed line %(fixed_example)s, for mobile %(mobile_example)s', code='invalid', params={ 'fixed_example': fixed if fixed else 'no example', 'mobile_example': mobile if mobile else 'no example' } ) except NumberParseException as ex: raise validation_error_class(str(ex)) except validation_error_class as ex: raise ex return value
def from_string(self, _string): """ :type _string:str """ self.country_code, self.phone_number = _string.strip().split(' ', maxsplit=1) self.region_code = phonenumbers.region_code_for_country_code(int(self.country_code)) return self
def scan(InputNumber, print_results=True): test('Running local scan...') FormattedPhoneNumber = "+" + formatNumber(InputNumber) try: PhoneNumberObject = phonenumbers.parse(FormattedPhoneNumber, None) except Exception as e: throw(e) 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] numberCountry = phonenumbers.region_code_for_country_code( int(numberCountryCode)) localNumber = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace( numberCountryCode, '') internationalNumber = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL) country = geocoder.country_name_for_number(PhoneNumberObject, "en") location = geocoder.description_for_number(PhoneNumberObject, "en") carrierName = carrier.name_for_number(PhoneNumberObject, 'en') if print_results: plus('International format: {}'.format(internationalNumber)) plus('Local format: {}'.format(localNumber)) plus('Country found: {} ({})'.format(country, numberCountryCode)) plus('City/Area: {}'.format(location)) plus('Carrier: {}'.format(carrierName)) for timezoneResult in timezone.time_zones_for_number( PhoneNumberObject): plus('Timezone: {}'.format(timezoneResult)) if phonenumbers.is_possible_number(PhoneNumberObject): plus('The number is valid and possible!') else: warn('The number is valid but might not be possible.') numberObj = {} numberObj['input'] = InputNumber numberObj['default'] = number numberObj['local'] = localNumber numberObj['international'] = internationalNumber numberObj['country'] = country numberObj['countryCode'] = numberCountryCode numberObj['countryIsoCode'] = numberCountry numberObj['location'] = location numberObj['carrier'] = carrierName return numberObj
def tz_ids_for_phone(phone, country='US'): """ Get the TZ identifiers that a phone number might be related to, e.g. >>> tztrout.tz_ids_for_phone('+16503334444') [u'America/Los_Angeles'] >>> tztrout.tz_ids_for_phone('+49 (0)711 400 40990') [u'Europe/Berlin', u'Europe/Busingen'] """ from phonenumbers.geocoder import description_for_number try: phone = phonenumbers.parse(phone, country) except: pass else: country_iso = phonenumbers.region_code_for_number(phone) if not country_iso: country_iso = phonenumbers.region_code_for_country_code( phone.country_code) if country_iso == 'US': # check if we have a specific exception for a given area code first exception_key = 'areacode:%s' % str(phone.national_number)[:3] if exception_key in data_exceptions: return data_exceptions[exception_key]['include'] state = city = None area = description_for_number(phone, 'en').split(',') if len(area) == 2: city = area[0].strip() state = area[1].strip() elif len(area) == 1 and area[0]: state = area[0].lower().strip() state = td.normalized_states['US'].get(state, None) return tz_ids_for_address(country_iso, state=state, city=city) elif country_iso == 'CA': area_code = str(phone.national_number)[:3] state = td.ca_area_code_to_state.get(area_code) return td.ca_state_to_tz_ids.get(state) elif country_iso == 'AU': area_code = str(phone.national_number)[:2] state = td.au_area_code_to_state.get(area_code) # Some Australian number prefixes (e.g. 04) are country-wide - fall # back to all the AU tz ids if state: return td.au_state_to_tz_ids.get(state) return pytz.country_timezones.get(country_iso) elif country_iso: return pytz.country_timezones.get(country_iso) return []
def tz_ids_for_phone(phone, country='US'): """ Get the TZ identifiers that a phone number might be related to, e.g. >>> tztrout.tz_ids_for_phone('+16503334444') [u'America/Los_Angeles'] >>> tztrout.tz_ids_for_phone('+49 (0)711 400 40990') [u'Europe/Berlin', u'Europe/Busingen'] """ from phonenumbers.geocoder import description_for_number try: phone = phonenumbers.parse(phone, country) except: pass else: country_iso = phonenumbers.region_code_for_number(phone) if not country_iso: country_iso = phonenumbers.region_code_for_country_code(phone.country_code) if country_iso == 'US': # check if we have a specific exception for a given area code first exception_key = 'areacode:%s' % str(phone.national_number)[:3] if exception_key in data_exceptions: return data_exceptions[exception_key]['include'] state = city = None area = description_for_number(phone, 'en').split(',') if len(area) == 2: city = area[0].strip() state = area[1].strip() elif len(area) == 1 and area[0]: state = area[0].lower().strip() state = td.normalized_states['US'].get(state, None) return tz_ids_for_address(country_iso, state=state, city=city) elif country_iso == 'CA': area_code = str(phone.national_number)[:3] state = td.ca_area_code_to_state.get(area_code) return td.ca_state_to_tz_ids.get(state) elif country_iso == 'AU': area_code = str(phone.national_number)[:2] state = td.au_area_code_to_state.get(area_code) # Some Australian number prefixes (e.g. 04) are country-wide - fall # back to all the AU tz ids if state: return td.au_state_to_tz_ids.get(state) return pytz.country_timezones.get(country_iso) elif country_iso: return pytz.country_timezones.get(country_iso) return []
def from_string(self, _string): """ :type _string:str """ self.country_code, self.phone_number = _string.strip().split( ' ', maxsplit=1) self.region_code = phonenumbers.region_code_for_country_code( int(self.country_code)) return self
def parse_phone_number(phone_number_str, phone_country_code): try: region_code = phonenumbers.region_code_for_country_code( int(phone_country_code)) phone_number = PhoneNumber(phone_number_str, region_code) return phone_number except ValueError: return None except NumberParseException: return None
def set_receivers(self, phone_numbers: list): self._receivers = {} config = self.reader.get_sms_config(self.identifier) for item in phone_numbers: country_code = region_code_for_country_code(phone_number_parse(item).country_code) if country_code not in config.white_list_countries: continue if country_code not in self._receivers: self._receivers[country_code] = set() self._receivers[country_code].add(item)
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 Exception as e: 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] numberCountry = phonenumbers.region_code_for_country_code( int(numberCountryCode)) localNumber = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace( numberCountryCode, '0') internationalNumber = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL) country = geocoder.country_name_for_number(PhoneNumberObject, "en") location = geocoder.description_for_number(PhoneNumberObject, "en") carrierName = carrier.name_for_number(PhoneNumberObject, 'en') print(code_result + 'International format: {}'.format(internationalNumber)) print(code_result + 'Local format: 0{}'.format(localNumber)) print(code_result + 'Country found: {} ({})'.format(country, numberCountryCode)) print(code_result + 'City/Area: {}'.format(location)) print(code_result + 'Carrier: {}'.format(carrierName)) 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.')
def localScan(InputNumber): global number global localNumber global internationalNumber global numberCountryCode global numberCountry print(code_info + 'Executando verificação local...') FormattedPhoneNumber = "+" + formatNumber(InputNumber) try: PhoneNumberObject = phonenumbers.parse(FormattedPhoneNumber, None) except Exception as e: 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] numberCountry = phonenumbers.region_code_for_country_code( int(numberCountryCode)) localNumber = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace( numberCountryCode, '0') internationalNumber = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL) country = geocoder.country_name_for_number(PhoneNumberObject, "en") location = geocoder.description_for_number(PhoneNumberObject, "en") carrierName = carrier.name_for_number(PhoneNumberObject, 'en') print(code_result + f'Formato internacional:{B} {internationalNumber}') print(code_result + f'Formato local:{B} 0 {localNumber}') print(code_result + f'País: {B}{country} ({numberCountryCode})') print(code_result + f'Cidade/Estado:{B} {location}') print(code_result + f'Operadora:{B} {carrierName}') for timezoneResult in timezone.time_zones_for_number( PhoneNumberObject): print(code_result + f'Fuso horário:{B} {timezoneResult}') if phonenumbers.is_possible_number(PhoneNumberObject): print(code_info + 'O número é válido e possível.') else: print(code_warning + 'O número é válido, mas pode não ser possível.')
def join(self): #join user # join, badu bizzle, male, 25, accra print("Registering new user") profile = self.arguments if len(profile) < 4: user = self.get_user(self.sender_phone) if user is not None: if int(user['status']) == User.STATUS_DELETED: #reactivate user self.update_user(self.sender_phone, {User.KEY_STATUS: User.STATUS_ACTIVE}) self.reply = WhookAppResponse.ACCOUNT_ACTIVATED self.success = True else: self.reply = WhookAppResponse.REGISTERED_ALREADY self.success = True else: self.success = True self.reply = WhookAppResponse.SHOULD_REGISTER # None # WhookAppResponse.JOIN_INFO else: name = profile[0] gender = profile[1].lower() age = int(profile[2]) location = profile[3] phone = self.sender_phone user = User(phone=phone, name=name, gender=gender, age=age, location=location) #if self.user_exists(phone): # self.success = True # self.reply = WhookAppResponse.ALREADY_REGISTERED phone_number = phonenumbers.parse( ("+%s" % self.sender_phone.strip()), None) locale_code = phonenumbers.region_code_for_country_code( phone_number.country_code) country = pycountry.countries.get(alpha2=locale_code) user.country_name = country.name user.locale_code = locale_code if self.register_user(user): self.success = True self.reply = WhookAppResponse.REGISTER_SUCCESS else: self.success = True self.reply = None
def write(cls, *args): config = cls(1) if config.party_phonecountry: party_phonecountry_code = config.party_phonecountry.code else: party_phonecountry_code = '' super(Configuration, cls).write(*args) if config.party_phonecountry: party_phonecountry_code_new = config.party_phonecountry.code else: party_phonecountry_code_new = '' if phonenumbers and party_phonecountry_code_new != party_phonecountry_code: ContactMechanism = Pool().get('party.contact_mechanism') table = ContactMechanism.__table__() cursor = Transaction().connection.cursor() for contact in ContactMechanism.search([('type', 'in', _PHONE_TYPES)]): values = {} # value_compact use PhoneNumberFormat.E164 phonenumber = phonenumbers.parse(contact.value_compact) region_code = phonenumbers.region_code_for_country_code( phonenumber.country_code) if region_code == party_phonecountry_code: # consider phonenumber with extensions p.e. 918041213 ext.412 phonenumber = phonenumbers.parse(contact.value, region_code) value = phonenumbers.format_number( phonenumber, PhoneNumberFormat.INTERNATIONAL) cursor.execute( *table.update(columns=[table.value], values=[value], where=(table.id == contact.id))) elif region_code == party_phonecountry_code_new: phonenumber = phonenumbers.parse(contact.value) value = phonenumbers.format_number( phonenumber, PhoneNumberFormat.NATIONAL) cursor.execute( *table.update(columns=[table.value], values=[value], where=(table.id == contact.id)))
def parse_phone_number_by_sender_country_code(sender_number, number_to_parse): """this function attempts to format the given 'sent_number' into a phone_number, based on the the 'sender_number''s country code""" try: formatted_sender_number = phonenumbers.parse(sender_number, None) country_code = formatted_sender_number.country_code formatted_sent_number = phonenumbers.parse( number_to_parse, phonenumbers.region_code_for_country_code(country_code)) except phonenumbers.NumberParseException as e: log.error( 'parse_phone_number_by_sender_country_code: cant parse number with sender\'s country code' ) return None else: return phonenumbers.format_number(formatted_sent_number, phonenumbers.PhoneNumberFormat.E164)
def post(self, request, *args, **kwargs): form = TeamRegisterForm(request.POST or None) if form.is_valid(): if not request.user.is_owner: raise PermissionDenied user_manager = UserManager() password = user_manager.make_random_password() ph = parse(form.cleaned_data['phone']) region_code = region_code_for_country_code(ph.country_code) team_member = user_manager.create_user( customer=request.user.customer, username=form.cleaned_data['username'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], email=form.cleaned_data['email'], phone=form.cleaned_data['phone'], password=password, is_team=True, is_clinician=form.cleaned_data['is_clinician'], is_scheduler=form.cleaned_data['is_scheduler'], is_biller=form.cleaned_data['is_biller'], region_code=region_code, timezone=request.user.timezone, ) messages.success(request, 'Team member created successfully') ActivityStream(customer=self.request.user.customer, actor=self.request.user.username, verb='created_team_member', action_object=team_member.username).save() from clients.models import Client clients = get_objects_for_user(request.user, Client.CAN_VIEW, Client) for user in User.objects.filter(Q(is_owner=True) | Q(is_team=True)): assign_perm(Client.CAN_VIEW, user, clients) assign_perm(Client.CAN_EDIT, user, clients) assign_perm(Client.CAN_DELETE, user, clients) if user.is_clinician: assign_perm(Client.CAN_NOTES, user, clients) emailer.send_team_member_credential_email(team_member, password, self.request.user) return redirect('team-list') messages.error(request, 'There was an error creating Team member') context = {'form': form} return render(request, self.template, context)
def validate_phonenumber(self, field): data = field.data try: if not data.startswith("+"): # Maybe they forgot this? data = "+" + data parsed = phonenumbers.parse(data) except: flash("Please ensure you prefix the phone number with your country code.") raise ValidationError("This is not a valid phone number") if not phonenumbers.is_valid_number(parsed): flash("Please ensure you prefix the phone number with your country code.") raise ValidationError("This is not a valid phone number") if not carrier._is_mobile(phonenumberutil.number_type(parsed)): raise ValidationError("This phone number doesn't look like a mobile phone number") self.phonenumber_locale = phonenumbers.region_code_for_country_code(parsed.country_code)
def join(self): #join user # join, badu bizzle, male, 25, accra print("Registering new user") profile = self.arguments if len(profile) < 4: user = self.get_user(self.sender_phone) if user is not None: if int(user['status'])==User.STATUS_DELETED: #reactivate user self.update_user(self.sender_phone, {User.KEY_STATUS:User.STATUS_ACTIVE}) self.reply = WhookAppResponse.ACCOUNT_ACTIVATED self.success=True else: self.reply = WhookAppResponse.REGISTERED_ALREADY self.success = True else: self.success = True self.reply =WhookAppResponse.SHOULD_REGISTER# None # WhookAppResponse.JOIN_INFO else: name = profile[0] gender = profile[1].lower() age = int(profile[2]) location = profile[3] phone = self.sender_phone user = User(phone=phone, name=name, gender=gender, age=age, location=location) #if self.user_exists(phone): # self.success = True # self.reply = WhookAppResponse.ALREADY_REGISTERED phone_number = phonenumbers.parse(("+%s" % self.sender_phone.strip()), None) locale_code = phonenumbers.region_code_for_country_code(phone_number.country_code) country=pycountry.countries.get(alpha2=locale_code) user.country_name=country.name user.locale_code=locale_code if self.register_user(user): self.success = True self.reply = WhookAppResponse.REGISTER_SUCCESS else: self.success = True self.reply = None
def post(self, request): form = RegisterForm(request.POST or None) if form.is_valid(): formdata = form.cleaned_data.copy() formdata.pop('password2') formdata.pop('password') tenant = Customer() tenant.username = form.cleaned_data['username'] tenant.first_name = form.cleaned_data['first_name'] tenant.last_name = form.cleaned_data['last_name'] tenant.email = form.cleaned_data['email'] tenant.phone = form.cleaned_data['phone'] tenant.timezone = form.cleaned_data['timezone'] ph = parse(form.cleaned_data['phone']) region_code = region_code_for_country_code(ph.country_code) tenant.region_code = region_code tenant.save() print(tenant.__dict__) user_manager = UserManager() user_manager.create_user( customer=tenant, username=form.cleaned_data['username'], email=form.cleaned_data['email'], password=form.cleaned_data['password'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], phone=form.cleaned_data['phone'], is_owner=True, is_clinician=True, is_scheduler=True, is_biller=True, region_code=tenant.region_code, timezone=tenant.timezone, ) ActivityStream(customer=tenant, actor=form.cleaned_data['username'], verb='signed up').save() return redirect('login') # to be changed later context = {'form': form} return render(request, self.template, context)
def validate_phone_number(value, validation_error_class): """ :type value:fields.PhoneNumber :return: """ assert type( value ) is PhoneNumber, "%s instance was supplied instead of PhoneNumber " % ( type(value), ) try: value.region_code = phonenumbers.region_code_for_country_code( int(value.country_code)) value.google_phone_number = phonenumbers.parse(value.phone_number, value.region_code) value.country_code = value.google_phone_number.country_code if not phonenumbers.is_valid_number(value.google_phone_number): fixed = phonenumbers.format_number( phonenumbers.example_number_for_type( value.region_code, PhoneNumberType.FIXED_LINE), phonenumbers.PhoneNumberFormat.NATIONAL) mobile = phonenumbers.format_number( phonenumbers.example_number_for_type(value.region_code, PhoneNumberType.MOBILE), phonenumbers.PhoneNumberFormat.NATIONAL) raise validation_error_class( 'Invalid number. format example are: ' + 'for fixed line %(fixed_example)s, for mobile %(mobile_example)s', code='invalid', params={ 'fixed_example': fixed if fixed else 'no example', 'mobile_example': mobile if mobile else 'no example' }) except NumberParseException as ex: raise validation_error_class(str(ex)) except validation_error_class as ex: raise ex return value
def validate_phonenumber(self, field): data = field.data print("DATA: ", data) if not data: # Don't validate if nothing was provided return field try: if not data.startswith('+'): # Maybe they forgot this? data = '+' + data parsed = phonenumbers.parse(data) except: flash("Please ensure you prefix the phone number with your country code.") raise ValidationError("This is not a valid phone number") user = User.query.filter_by(phonenumber=data).first() if user and user.id != self.user.id: raise ValidationError("Phone number already on record.") if not phonenumbers.is_valid_number(parsed): flash("Please ensure you prefix the phone number with your country code.") raise ValidationError("This is not a valid phone number") if not carrier._is_mobile(phonenumberutil.number_type(parsed)): raise ValidationError("This phone number doesn't look like a mobile phone number") self.phonenumber_locale = phonenumbers.region_code_for_country_code(parsed.country_code)
def validate_phonenumber(self, field): data = field.data try: if not data.startswith('+'): # Maybe they forgot this? data = '+' + data parsed = phonenumbers.parse(data) except: flash( "Please ensure you prefix the phone number with your country code." ) raise ValidationError("This is not a valid phone number") if not phonenumbers.is_valid_number(parsed): flash( "Please ensure you prefix the phone number with your country code." ) raise ValidationError("This is not a valid phone number") if not carrier._is_mobile(phonenumberutil.number_type(parsed)): raise ValidationError( "This phone number doesn't look like a mobile phone number") self.phonenumber_locale = phonenumbers.region_code_for_country_code( parsed.country_code)
def get_region_code(self): """Returns the phonenumbers region code for this Mailbox's number""" parsed_number = phonenumbers.parse(self.phone_number) return phonenumbers.region_code_for_country_code(parsed_number.country_code)
def to_json(self): return '{"regionCode":"%s","countryCode":"%s","phoneNumber":"%s"}' % ( phonenumbers.region_code_for_country_code(int( self.country_code)), self.country_code, self.phone_number)
def to_json(self): return '{"regionCode":"%s","countryCode":"%s","phoneNumber":"%s"}' % ( phonenumbers.region_code_for_country_code(int(self.country_code)), self.country_code, self.phone_number )
# try: # es.indices.delete(index=INDEX) # except: # pass es.indices.create(index=INDEX,ignore=400) import phonenumbers import pycountry for r in range(0,500): phone = fake.phone_number().split("x")[0] Id = str(int("".join([ c if c.isdigit() else "" for c in phone]))) body = dict(phone=Id, name=fake.first_name(), age=random.choice(range(18,35)), gender=random.choice(['male','female']), location=fake.city(), status=random.choice([1,0]), status_message=" ".join(fake.text().split()[:10])) p = ("+%s" % Id.strip()) try: phone_number = phonenumbers.parse(p, None) locale_code = phonenumbers.region_code_for_country_code(phone_number.country_code) country=pycountry.countries.get(alpha2=locale_code) body['country_name'] = country.name body['locale_code'] = locale_code if not (es.exists(index=INDEX, doc_type=DOC, id=Id)): es.index(index=INDEX, doc_type=DOC, id=Id, body=body) except Exception as e: print "Error :%s" % str(e)
es = Elasticsearch([{u'host': u'127.0.0.1', u'port': b'9200'}]) # try: # es.indices.delete(index=INDEX) # except: # pass es.indices.create(index=INDEX, ignore=400) import phonenumbers import pycountry for r in range(0, 500): phone = fake.phone_number().split("x")[0] Id = str(int("".join([c if c.isdigit() else "" for c in phone]))) body = dict(phone=Id, name=fake.first_name(), age=random.choice(range(18, 35)), gender=random.choice(['male', 'female']), location=fake.city(), status=random.choice([1, 0]), status_message=" ".join(fake.text().split()[:10])) p = ("+%s" % Id.strip()) try: phone_number = phonenumbers.parse(p, None) locale_code = phonenumbers.region_code_for_country_code( phone_number.country_code) country = pycountry.countries.get(alpha2=locale_code) body['country_name'] = country.name body['locale_code'] = locale_code if not (es.exists(index=INDEX, doc_type=DOC, id=Id)): es.index(index=INDEX, doc_type=DOC, id=Id, body=body) except Exception as e: print "Error :%s" % str(e)