def extract_address(address: dict): """ Given an *address*, converts it to text and returns a result from the SmartyStreets US Extract API containing information about an address connected to the text. Assumes that *address* keys, where present, are sorted in the following order: * street * street2 * secondary * city * state * zipcode Note that this API is not consistent with the US Street API, and the lookup and responses must be handled differently. """ LOG.warning("Previous lookup failed. Looking up address as free text.") client = smartystreets_client_builder().build_us_extract_api_client() address_text = ', '.join([ str(val) for val in list(address.values()) if val ]) lookup = ExtractLookup() lookup.text = address_text result = client.send(lookup) addresses = result.addresses for address in addresses: if len(address.candidates) > 0: result = address.candidates return first_candidate_data(result) return {}
def extract_address(address: dict) -> dict: """ Given an *address*, converts it to text and returns a result from the SmartyStreets US Extract API containing information about an address connected to the text. Note that this API is not consistent with the US Street API, and the lookup and responses must be handled differently. """ LOG.debug("Making SmartyStreets extract API request") global EXTRACT_CLIENT if not EXTRACT_CLIENT: EXTRACT_CLIENT = smartystreets_client_builder( ).build_us_extract_api_client() address_text = ', '.join( [str(val) for val in list(address.values()) if val]) lookup = ExtractLookup() lookup.text = address_text result = EXTRACT_CLIENT.send(lookup) addresses = result.addresses for add in addresses: if len(add.candidates) > 0: return add.candidates return None
def run(): auth_id = "Your SmartyStreets Auth ID here" auth_token = "Your SmartyStreets Auth Token here" # We recommend storing your secret keys in environment variables instead---it's safer! # auth_id = os.environ['SMARTY_AUTH_ID'] # auth_token = os.environ['SMARTY_AUTH_TOKEN'] credentials = StaticCredentials(auth_id, auth_token) client = ClientBuilder(credentials).build_us_extract_api_client() text = "Here is some text.\r\nMy address is 3785 Las Vegs Av." \ "\r\nLos Vegas, Nevada." \ "\r\nMeet me at 1 Rosedale Baltimore Maryland, not at 123 Phony Street, Boise Idaho." # Documentation for input fields can be found at: # https://smartystreets.com/docs/cloud/us-extract-api#http-request-input-fields lookup = ExtractLookup() lookup.text = text lookup.aggressive = True lookup.addresses_have_line_breaks = False lookup.addresses_per_line = 1 result = client.send(lookup) metadata = result.metadata print('Found {} addresses.'.format(metadata.address_count)) print('{} of them were valid.'.format(metadata.verified_count)) print() addresses = result.addresses print('Addresses: \r\n**********************\r\n') for address in addresses: print('"{}"\n'.format(address.text)) print('Verified? {}'.format(address.verified)) if len(address.candidates) > 0: print('\nMatches:') for candidate in address.candidates: print(candidate.delivery_line_1) print(candidate.last_line) print() else: print() print('**********************\n')
def test_reject_blank_lookup(self): capturing_sender = RequestCapturingSender() sender = URLPrefixSender('http://localhost/', capturing_sender) serializer = FakeSerializer(None) client = Client(sender, serializer) self.assertRaises(SmartyException, client.send, Lookup())
def verifyUserInput(): addr = request.args.get("text") auth_id = "4db04845-3fbe-8b38-d005-5dc10f75a80b" auth_token = "pAKyFrPrrfishQdMPgzU" credentials = StaticCredentials(auth_id, auth_token) client = ClientBuilder(credentials).build_us_extract_api_client() lookup = ExtractLookup() lookup.text = addr lookup.aggressive = True lookup.addresses_have_line_breaks = False lookup.addresses_per_line = 1 result = client.send(lookup) metadata = result.metadata print("Found {} addresses.".format(metadata.address_count)) print("{} of them were valid.".format(metadata.verified_count)) print() return jsonify(metadata.verified_count)
def test_content_type_set_correctly(self): sender = RequestCapturingSender() serializer = FakeSerializer(None) client = Client(sender, serializer) lookup = Lookup("Hello, World!") client.send(lookup) self.assertEqual("text/plain", sender.request.content_type)
def test_deserialize_called_with_response_body(self): response = Response('Hello, World!', 0) sender = MockSender(response) deserializer = FakeDeserializer({}) client = Client(sender, deserializer) client.send(Lookup('Hello, World!')) self.assertEqual(response.payload, deserializer.input)
def test_sending_body_only_lookup(self): capturing_sender = RequestCapturingSender() sender = URLPrefixSender('http://localhost/', capturing_sender) serializer = FakeSerializer(None) client = Client(sender, serializer) expected_payload = 'Hello, World!' client.send(Lookup('Hello, World!')) self.assertEqual(expected_payload, capturing_sender.request.payload)
def test_result_correctly_assigned_to_corresponding_lookup(self): raw_result = {"meta": {}, "addresses": [{"text": "Hello, World!"}]} expected_result = Result(raw_result) lookup = Lookup('Hello, World!') sender = MockSender(Response('[]', 0)) deserializer = FakeDeserializer(raw_result) client = Client(sender, deserializer) client.send(lookup) self.assertEqual(expected_result.addresses[0].text, lookup.result.addresses[0].text)
def run(): auth_id = "Your SmartyStreets Auth ID here" auth_token = "Your SmartyStreets Auth Token here" # We recommend storing your secret keys in environment variables instead---it's safer! # auth_id = os.environ['SMARTY_AUTH_ID'] # auth_token = os.environ['SMARTY_AUTH_TOKEN'] credentials = StaticCredentials(auth_id, auth_token) client = ClientBuilder(credentials).build_us_extract_api_client() text = "Here is some text.\r\nMy address is 3785 Las Vegs Av." \ "\r\nLos Vegas, Nevada." \ "\r\nMeet me at 1 Rosedale Baltimore Maryland, not at 123 Phony Street, Boise Idaho." lookup = Lookup(text) result = client.send(lookup) metadata = result.metadata print('Found {} addresses.'.format(metadata.address_count)) print('{} of them were valid.'.format(metadata.verified_count)) print() addresses = result.addresses print('Addresses: \r\n**********************\r\n') for address in addresses: print('"{}"\n'.format(address.text)) print('Verified? {}'.format(address.verified)) if len(address.candidates) > 0: print('\nMatches:') for candidate in address.candidates: print(candidate.delivery_line_1) print(candidate.last_line) print() else: print() print('**********************\n')
def run(): auth_id = os.environ[ 'SMARTY_AUTH_ID'] # We recommend storing your keys in environment variables auth_token = os.environ['SMARTY_AUTH_TOKEN'] credentials = StaticCredentials(auth_id, auth_token) client = ClientBuilder(credentials).build_us_extract_api_client() text = "Here is some text.\r\nMy address is 73 Saint Pauls Pl Brooklyn ny" lookup = Lookup(text) result = client.send(lookup) metadata = result.metadata print('Found {} addresses.'.format(metadata.address_count)) print('{} of them were valid.'.format(metadata.verified_count)) print() addresses = result.addresses print('Addresses: \r\n**********************\r\n') for address in addresses: print('"{}"\n'.format(address.text)) print('Verified? {}'.format(address.verified)) if len(address.candidates) > 0: print('\nMatches:') for candidate in address.candidates: print(candidate.delivery_line_1) print(candidate.last_line) print() else: print() print('**********************\n')
def test_sending_fully_populated_lookup(self): capturing_sender = RequestCapturingSender() sender = URLPrefixSender('http://localhost/', capturing_sender) serializer = FakeSerializer(None) client = Client(sender, serializer) lookup = Lookup('1') lookup.html = True lookup.aggressive = True lookup.addresses_have_line_breaks = True lookup.addresses_per_line = 2 client.send(lookup) request = capturing_sender.request self.assertEqual('true', request.parameters['html']) self.assertEqual('true', request.parameters['aggressive']) self.assertEqual('true', request.parameters['addr_line_breaks']) self.assertEqual(2, request.parameters['addr_per_line'])
def varify_address(address_string): auth_id = "c7bce886-bfac-637c-31f2-dff34a511bf7" auth_token = "r895zvHWv7B9Ew1cmwTA" # We recommend storing your secret keys in environment variables instead---it's safer! # auth_id = os.environ['SMARTY_AUTH_ID'] # auth_token = os.environ['SMARTY_AUTH_TOKEN'] credentials = StaticCredentials(auth_id, auth_token) client = ClientBuilder(credentials).build_us_extract_api_client() text = address_string # Documentation for input fields can be found at: # https://smartystreets.com/docs/cloud/us-extract-api#http-request-input-fields lookup = ExtractLookup() lookup.text = text lookup.aggressive = True lookup.addresses_have_line_breaks = False lookup.addresses_per_line = 1 result = client.send(lookup) metadata = result.metadata # print('Found {} addresses.'.format(metadata.address_count)) # print('{} of them were valid.'.format(metadata.verified_count)) # print() addresses = result.addresses for address in addresses: print('"{}"\n'.format(address.text)) print('Verified? {}'.format(address.verified)) data = {} if len(address.candidates) > 0: try: data['Ship-to Address'] = ( address.candidates[0].components.primary_number + ' ' + address.candidates[0].components.street_name + ' ' + address.candidates[0].components.street_suffix) try: data['Ship-to Address 2'] = ( address.candidates[0].components.secondary_designator + ' ' + address.candidates[0].components.secondary_number) except Exception as e: print('error in add 2') print(e) data['Ship-to Address 2'] = "" data['Ship-to City'] = ( address.candidates[0].components.city_name) data['Ship-to County'] = ( address.candidates[0].components.state_abbreviation) data['Ship-to Post-code'] = ( address.candidates[0].components.zipcode + '-' + address.candidates[0].components.plus4_code) data['Ship-to Country/Region Code'] = ('US') except Exception as e: return False return data return False # if __name__ == "__main__": # run()
def test_raises_exception_when_response_has_error(self): exception = exceptions.BadCredentialsError client = Client(MockExceptionSender(exception), FakeSerializer(None)) self.assertRaises(exception, client.send, Lookup(text='test'))