def send_lookup(self, lookup): """ Sends a Lookup object to the US Street API and stores the result in the Lookup's result field. """ batch = Batch() batch.add(lookup) self.send_batch(batch)
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_street_api_client() batch = Batch() batch.add(Lookup()) batch[0].street = "1600 amphitheatre parkway" batch[0].city = "Mountain view" batch[0].state = "california" batch.add(Lookup( "1 Rosedale, Baltimore, Maryland")) # Freeform addresses work too. batch[ 1].candidates = 10 # Allows up to ten possible matches to be returned (default is 1). batch.add(Lookup("123 Bogus Street, Pretend Lake, Oklahoma")) batch.add(Lookup()) batch[3].street = "1 Infinite Loop" batch[ 3].zipcode = "95014" # You can just input the street and ZIP if you want. assert len(batch) == 4 try: client.send_batch(batch) except exceptions.SmartyException as err: print(err) return for i, lookup in enumerate(batch): candidates = lookup.result if len(candidates) == 0: print("Address {} is invalid.\n".format(i)) continue print( "Address {} is valid. (There is at least one candidate)".format(i)) for candidate in candidates: components = candidate.components metadata = candidate.metadata print("\nCandidate {} : ".format(candidate.candidate_index)) print("Delivery line 1: {}".format(candidate.delivery_line_1)) print("Last line: {}".format(candidate.last_line)) print("ZIP Code: {}-{}".format(components.zipcode, components.plus4_code)) print("County: {}".format(metadata.county_name)) print("Latitude: {}".format(metadata.latitude)) print("Longitude: {}".format(metadata.longitude)) print("")
def test_successfully_sends_batch(self): expected_payload = "Hello, World!" sender = RequestCapturingSender() serializer = FakeSerializer(expected_payload) client = Client(sender, serializer) batch = Batch() batch.add(Lookup()) batch.add(Lookup()) client.send_batch(batch) self.assertEqual(expected_payload, sender.request.payload)
def test_empty_batch_not_sent(self): sender = RequestCapturingSender() client = Client(sender, None) client.send_batch(Batch()) self.assertIsNone(sender.request)
def test_results_correctly_assigned_to_corresponding_lookup(self): raw_results = [{"input_index": 0}, {"input_index": 1}] expected_results = [Result(raw_results[0]), Result(raw_results[1])] batch = Batch() batch.add(Lookup()) batch.add(Lookup()) sender = MockSender(Response("[]", 0)) deserializer = FakeDeserializer(raw_results) client = Client(sender, deserializer) client.send_batch(batch) self.assertEqual(expected_results[0].input_index, batch[0].result.input_index) self.assertEqual(expected_results[1].input_index, batch[1].result.input_index)
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_zipcode_api_client() batch = Batch() batch.add(Lookup()) batch[ 0].zipcode = "12345" # A Lookup may have a ZIP Code, city and state, or city, state, and ZIP Code batch.add(Lookup()) batch[1].city = "Phoenix" batch[1].state = "Arizona" batch.add(Lookup("cupertino", "CA", "95014")) # You can also set these with arguments assert len(batch) == 3 try: client.send_batch(batch) except exceptions.SmartyException as err: print(err) return for i, lookup in enumerate(batch): result = lookup.result print("Lookup {}:\n".format(i)) if result.status is not None: print("Status: " + result.status) print("Reason: " + result.reason) continue cities = result.cities print("{} City and State match(es):".format(len(cities))) for city in cities: print("City: " + city.city) print("State: " + city.state) print("Mailable City: {}".format(city.mailable_city)) print("") zipcodes = result.zipcodes print("{} ZIP Code match(es):".format(len(zipcodes))) for zipcode in zipcodes: print("ZIP Code: " + zipcode.zipcode) print("County: " + zipcode.county_name) print("Latitude: {}".format(zipcode.latitude)) print("Longitude: {}".format(zipcode.longitude)) print("") print("***********************************")
def batches_from_streets(streets, size=100): batches = [] start = 0 offset = len(streets) % size params = {'city': 'Chicago', 'state': 'Illinois', 'candidates': 5} while streets: batch = Batch() streets_batch = (streets.pop().strip().title() for i in range(offset - start)) [batch.add(Lookup(s, **params)) for s in streets_batch] offset = size batches.append(batch) return batches
def test_candidates_correctly_assigned_to_corresponding_lookup(self): candidate0 = { 'input_index': 0, 'candidate_index': 0, 'addressee': 'Mister 0' } candidate1 = { 'input_index': 1, 'candidate_index': 0, 'addressee': 'Mister 1' } candidate2 = { 'input_index': 1, 'candidate_index': 1, 'addressee': 'Mister 2' } raw_candidates = [candidate0, candidate1, candidate2] expected_candidates = [ Candidate(candidate0), Candidate(candidate1), Candidate(candidate2) ] batch = Batch() batch.add(Lookup()) batch.add(Lookup()) sender = MockSender(Response("[]", 0)) deserializer = FakeDeserializer(raw_candidates) client = Client(sender, deserializer) client.send_batch(batch) self.assertEqual(expected_candidates[0].addressee, batch[0].result[0].addressee) self.assertEqual(expected_candidates[1].addressee, batch[1].result[0].addressee) self.assertEqual(expected_candidates[2].addressee, batch[1].result[1].addressee)
def __prepare_smarty_request_list(self, address_list): """ Returns a list of requests each containing SmartyAddressService.MAX_ADDRESSES_PER_REQUEST address input strings. Input Address strings are converted smarty street Lookup objects. The request list is a list of batch partitions, smarty street Batch objects, which serves as the overall address batch. """ single_request_batch_partition = Batch() addresses_per_request = 0 request_list = [] for address in address_list: if addresses_per_request == SmartyAddressService.MAX_ADDRESSES_PER_REQUEST: request_list.append(single_request_batch_partition) single_request_batch_partition = Batch() addresses_per_request = 0 single_request_batch_partition.add(Lookup(address.input_string)) self.__total_addresses_in_request_list += 1 addresses_per_request += 1 if addresses_per_request > 0: request_list.append(single_request_batch_partition) return request_list
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_zipcode_api_client() batch = Batch() # Documentation for input fields can be found at: # https://smartystreets.com/docs/us-zipcode-api#input-fields batch.add(ZIPCodeLookup()) batch[0].input_id = "011889998819991197253" # Optional ID from your system batch[ 0].zipcode = "12345" # A Lookup may have a ZIP Code, city and state, or city, state, and ZIP Code batch.add(ZIPCodeLookup()) batch[1].city = "Phoenix" batch[1].state = "Arizona" batch.add(ZIPCodeLookup("cupertino", "CA", "95014")) # You can also set these with arguments assert len(batch) == 3 try: client.send_batch(batch) except exceptions.SmartyException as err: print(err) return for i, lookup in enumerate(batch): result = lookup.result print("Lookup {}:\n".format(i)) if result.status is not None: print("Status: " + result.status) print("Reason: " + result.reason) continue cities = result.cities print("{} City and State match(es):".format(len(cities))) for city in cities: print("City: " + city.city) print("State: " + city.state) print("Mailable City: {}".format(city.mailable_city)) print("") zipcodes = result.zipcodes print("{} ZIP Code match(es):".format(len(zipcodes))) for zipcode in zipcodes: print("ZIP Code: " + zipcode.zipcode) print("County: " + zipcode.county_name) print("Latitude: {}".format(zipcode.latitude)) print("Longitude: {}".format(zipcode.longitude)) print("") print("***********************************")
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_street_api_client() batch = Batch() # Documentation for input fields can be found at: # https://smartystreets.com/docs/us-street-api#input-fields batch.add(StreetLookup()) batch[0].input_id = "24601" # Optional ID from your system batch[0].addressee = "John Doe" batch[0].street = "1600 amphitheatre parkway" batch[0].street2 = "closet under the stairs" batch[0].secondary = "APT 2" batch[0].urbanization = "" # Only applies to Puerto Rico addresses batch[0].lastline = "Mountain view, california" batch[0].candidates = 5 batch[0].match = "invalid" # "invalid" is the most permissive match, # this will always return at least one result even if the address is invalid. # Refer to the documentation for additional Match Strategy options. batch.add(StreetLookup( "1 Rosedale, Baltimore, Maryland")) # Freeform addresses work too. batch[ 1].candidates = 10 # Allows up to ten possible matches to be returned (default is 1). batch.add(StreetLookup("123 Bogus Street, Pretend Lake, Oklahoma")) batch.add(StreetLookup()) batch[3].input_id = "8675309" batch[3].street = "1 Infinite Loop" batch[ 3].zipcode = "95014" # You can just input the street and ZIP if you want. batch[3].candidates = 1 assert len(batch) == 4 try: client.send_batch(batch) except exceptions.SmartyException as err: print(err) return for i, lookup in enumerate(batch): candidates = lookup.result if len(candidates) == 0: print("Address {} is invalid.\n".format(i)) continue print( "Address {} is valid. (There is at least one candidate)".format(i)) for candidate in candidates: components = candidate.components metadata = candidate.metadata print("\nCandidate {} : ".format(candidate.candidate_index)) print("Delivery line 1: {}".format(candidate.delivery_line_1)) print("Last line: {}".format(candidate.last_line)) print("ZIP Code: {}-{}".format(components.zipcode, components.plus4_code)) print("County: {}".format(metadata.county_name)) print("Latitude: {}".format(metadata.latitude)) print("Longitude: {}".format(metadata.longitude)) print("")
def setUp(self): self.batch = Batch()
class TestBatch(unittest.TestCase): def setUp(self): self.batch = Batch() def test_gets_lookup_by_input_id(self): lookup = us_street.Lookup() lookup.input_id = "has input id" self.batch.add(lookup) self.assertEqual(lookup, self.batch.get_by_input_id('has input id')) def test_gets_lookup_by_index(self): lookup = us_street.Lookup() self.batch.add(lookup) self.assertEqual(lookup, self.batch[0]) def test_returns_correct_size(self): self.batch.add(us_street.Lookup()) self.batch.add(us_street.Lookup()) self.batch.add(us_street.Lookup()) self.assertEqual(3, len(self.batch)) def test_clear_method_clears_both_lookup_collections(self): lookup = us_street.Lookup() lookup.input_id = "test" self.batch.add(lookup) self.batch.clear() self.assertEqual(0, len(self.batch.all_lookups)) self.assertEqual(0, len(self.batch.named_lookups)) def test_adding_a_lookup_when_batch_is_full_raises_exception(self): lookup = us_street.Lookup() for i in range(0, Batch.MAX_BATCH_SIZE): self.batch.add(lookup) self.assertRaises(BatchFullError, self.batch.add, lookup)