def smarty_validate(address):
    load_dotenv()
    auth_id = os.environ['SMARTY_AUTH_ID']
    auth_token = os.environ['SMARTY_AUTH_TOKEN']
    write_path = '/Users/wesamazaizeh/Desktop/Projects/halal_o_meter/src/data/data_collection/invalid_address.txt'
    credentials = StaticCredentials(auth_id, auth_token)
    client = ClientBuilder(credentials).build_us_street_api_client()

    lookup = StreetLookup()
    lookup.street = address
    lookup.match = "strict"
    try:
        client.send_lookup(lookup)
    except exceptions.SmartyException as err:
        print(err)
        return

    result = lookup.result
    if not result:
        print("\nInvalid address.")
        print(address)
        # with open(write_path, 'a+') as myfile:
        #     myfile.write("{}\n".format(address))
        return
    return result
示例#2
0
 def __isValidDeliveryStreet(self, deliveryStreet, deliveryZip):  
     '''Performs a validity check of a given street address and zip code pair.  Leverages the SmartyStreets 
     address verification service.
     
     Args:
         self: Instance reference 
         deliveryStreet: String containing the street address
         deliveryZip: String containing the zip code
     
     Returns:
         Boolean indicating whether the street address is valid
     
     Raises:
         None
     '''
     if deliveryStreet and deliveryZip:
         credentials = StaticCredentials(AUTH_ID, AUTH_TOKEN)
         client = ClientBuilder(credentials).build_us_street_api_client()
         lookup = Lookup()
         lookup.street = deliveryStreet
         lookup.zipcode = deliveryZip
         try:
             client.send_lookup(lookup)
         except exceptions.SmartyException:
             return False
         
         if lookup.result:
             return True
         else:
             return False
     else:
         return False
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()
    # client = ClientBuilder(credentials).with_proxy('localhost:8080', 'user', 'password').build_us_street_api_client()
    # Uncomment the line above to try it with a proxy instead

    lookup = Lookup()
    lookup.street = "1600 Amphitheatre Pkwy"
    lookup.city = "Mountain View"
    lookup.state = "CA"

    try:
        client.send_lookup(lookup)
    except exceptions.SmartyException as err:
        print(err)
        return

    result = lookup.result

    if not result:
        print("No candidates. This means the address is not valid.")
        return

    first_candidate = result[0]

    print("Address is valid. (There is at least one candidate)\n")
    print("ZIP Code: " + first_candidate.components.zipcode)
    print("County: " + first_candidate.metadata.county_name)
    print("Latitude: {}".format(first_candidate.metadata.latitude))
    print("Longitude: {}".format(first_candidate.metadata.longitude))
示例#4
0
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)
示例#6
0
 def __init__(self):
     self.auth_id = '839867c5-ea75-9d4f-10da-85b8fd453ba9'
     self.auth_token = 'uU5o6MjSolIc00dxVYeA'
     self.credentials = StaticCredentials(self.auth_id, self.auth_token)
     self.client = ClientBuilder(
         self.credentials).build_us_street_api_client()
     self.lookup = Lookup()
示例#7
0
def test_address(address):
    auth_id = "9484953c-80e6-c55d-c6fc-317df18233eb"
    auth_token = "GdjMKksY6pLKQFoLMiWx"
    credentials = StaticCredentials(auth_id, auth_token)
    client = ClientBuilder(credentials).build_us_street_api_client()
    lookup = Lookup()
    lookup.street = address['street']
    lookup.city = address['city']
    lookup.state = address['state']
    lookup.zipcode = address['zipcode']
    lookup.match = "Invalid"  # "invalid" is the most permissive match

    try:
        client.send_lookup(lookup)
    except exceptions.SmartyException as err:
        print(err)
        return

    result = lookup.result

    if not result:
        print("No candidates. This means the address is not valid.")
        return False

    first_candidate = result[0]

    print("Address is valid. (There is at least one candidate)\n")
    print("ZIP Code: " + first_candidate.components.zipcode)
    print("County: " + first_candidate.metadata.county_name)
    print("Latitude: {}".format(first_candidate.metadata.latitude))
    print("Longitude: {}".format(first_candidate.metadata.longitude))
    return True
    def test_deserialize_called_with_response_body(self):
        response = Response("Hello, World!", 0)
        sender = MockSender(response)
        deserializer = FakeDeserializer(None)
        client = Client(sender, deserializer)

        client.send_lookup(Lookup())

        self.assertEqual(response.payload, deserializer.input)
def verifyaddress():
    body = json.loads(request.data.decode())
    credentials = StaticCredentials(AUTH_ID, AUTH_TOKEN)
    client = ClientBuilder(credentials).build_us_street_api_client()

    lookup = StreetLookup()
    # lookup.addressee = body.get('address')
    lookup.street = body['street']
    # lookup.secondary = body.get('secondary')
    lookup.city = body['city']
    lookup.state = body['state']
    lookup.zipcode = body['zipcode']
    lookup.candidates = 1

    try:
        client.send_lookup(lookup)
    except Exception.SmartyException as err:
        print(err)
        return Response([], status=500)

    results = lookup.result
    if not results:
        return Response(json.dumps(False, default=str), status=200, content_type="text/json")
    first_candidate = results[0]
    # city_name, state_abbreviation, zipcode

    if not first_candidate or (first_candidate.delivery_line_1 != body['street'] or
                               first_candidate.components.city_name != body['city'] or
                               first_candidate.components.state_abbreviation != body['state']
                               or first_candidate.components.zipcode != body['zipcode']):
        print("No candidates. This means the address is not valid.")
        return Response(json.dumps(False, default=str), status=200, content_type="text/json")

    return Response(json.dumps(True, default=str), status=200, content_type="text/json")
示例#10
0
def run(addressee,street,city,state,zipcode):
    auth_id = "9a7b8041-9ac4-7e15-75b0-780771fc3d92"
    auth_token = "xMvDBs26P88X0Esk8q5D"

    # 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()
    # client = ClientBuilder(credentials).with_custom_header({'User-Agent': 'smartystreets ([email protected])', 'Content-Type': 'application/json'}).build_us_street_api_client()
    # client = ClientBuilder(credentials).with_proxy('localhost:8080', 'user', 'password').build_us_street_api_client()
    # Uncomment the line above to try it with a proxy instead

    # Documentation for input fields can be found at:
    # https://smartystreets.com/docs/us-street-api#input-fields

    lookup = StreetLookup()
    # lookup.input_id = ""  # Optional ID from your system
    lookup.addressee = addressee
    lookup.street = street
    lookup.street2 = ""
    # lookup.secondary = secondary
    # lookup.urbanization = ""  # Only applies to Puerto Rico addresses
    lookup.city = city
    lookup.state = state
    lookup.zipcode = zipcode
    # # lookup.candidates = 3
    lookup.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.

    try:
        client.send_lookup(lookup)
    except exceptions.SmartyException as err:
        print(err)
        return

    result = lookup.result
    # print(result[0])
   
    

    if not result:
        print("No candidates. This means the address is not valid.")
        return False
    else:
        print("correct address")
        return True
示例#11
0
    def do_lookup(cls, address_dto):
        creds = cls.get_credentials()
        client = ClientBuilder(creds).with_licenses(
            ["us-standard-cloud"]).build_us_street_api_client()

        lookup = StreetLookup()

        lookup = StreetLookup()
        # lookup.input_id = "24601"  # Optional ID from your system

        lookup.street = "1047 East Washington Street"
        # lookup.street2 = "closet under the stairs"
        # lookup.secondary = "APT 2"
        # lookup.urbanization = ""  # Only applies to Puerto Rico addresses
        lookup.city = "Pembroke"
        lookup.state = "MA"
        # lookup.zipcode = ""
        lookup.candidates = 3
        client.send_lookup(lookup)

        try:
            client.send_lookup(lookup)
        except exceptions.SmartyException as err:
            print(err)
            cls.candidates = None
            return

        cls.candidates = lookup.result
        cls._set_dictionary()
def t2():

    lookup = StreetLookup()
    # lookup.input_id = "24601"  # Optional ID from your system

    lookup.street = "21 Hoyt"
    # lookup.street2 = "closet under the stairs"
    #lookup.secondary = "APT 2"
    #lookup.urbanization = ""  # Only applies to Puerto Rico addresses
    lookup.city = "S Salem"
    lookup.state = "NY"
    # lookup.zipcode = "02341"
    lookup.candidates = 3
    # lookup.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.

    sm_adaptor = SmartyStreetsAdaptor()
    sm_adaptor.do_lookup(lookup)
    j_result = sm_adaptor.to_json()

    print("T1 result = \n", json.dumps(j_result, indent=2, default=str))
def us_street_lookup(address: dict) -> Lookup:
    """
    Creates and returns a SmartyStreets US Street API Lookup object for a given
    *address*.

    Raises a :class:`InvalidAddressMappingError` if a Lookup property from the
    SmartyStreets geocoding API is not present in the given *address* data.
    """
    lookup = Lookup()
    try:
        lookup.street = address['street']
        lookup.street2 = address['street2']
        lookup.secondary = address['secondary']
        lookup.city = address['city']
        lookup.state = address['state']
        lookup.zipcode = address['zipcode']
    except KeyError as e:
        raise InvalidAddressMappingError(e)

    lookup.candidates = 1
    lookup.match = "Invalid"  # Most permissive
    return lookup
    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)
示例#15
0
def zip9_lookup_by_components(address):
    lookup = Lookup()
    street_number = address.get("street_number")
    street = address.get("street")
    lookup.street = f"{street_number} {street}"
    lookup.city = address.get("city")
    lookup.state = address.get("state")
    lookup.zipcode = address.get("zip5")
    return zip9_lookup(lookup)
示例#16
0
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
示例#17
0
def run():
    auth_id = '1d3ba9eb-6df4-74ec-fa31-d23fe2d89162'
    auth_token = '5RqNDBSfOAq3jdN7OgMc'

    # 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()
    # client = ClientBuilder(credentials).with_proxy('localhost:8080', 'user', 'password').build_us_street_api_client()
    # Uncomment the line above to try it with a proxy instead

    address = '350 S Main, Salt Lake City, UT, 84101'
    lookup = Lookup(address)
    #lookup.street = "1600 Amphitheatre Pkwy"
    #lookup.city = "Mountain View"
    #lookup.state = "CA"
    #lookup.street = 'Union Station, 1717 Pacific Ave, #2100, Tacoma, WA 98402'

    try:
        client.send_lookup(lookup)
    except exceptions.SmartyException as err:
        print(err)
        return

    result = lookup.result

    if not result:
        print("No candidates. This means the address is not valid.")
        return

    first_candidate = result[0]

    print("Address is valid. (There is at least one candidate)\n")
    print("ZIP Code: " + first_candidate.components.zipcode)
    print("County: " + first_candidate.metadata.county_name)
    print("Latitude: {}".format(first_candidate.metadata.latitude))
    print("Longitude: {}".format(first_candidate.metadata.longitude))
示例#18
0
def smarty_api(flat_address_list: List[str]) -> Optional[SmartyStreetResult]:
    """
  Run addresses through SmartyStreets API, returning a `SmartyStreetsResult`
  object with all the information we get from the API.
  If any errors occur, we'll return None.
  Args:
      flat_address_list: a flat list of addresses that will be read as follows:
        _ : an unused arguement for ID
        street: The street address, e.g., 250 OCONNOR ST
        state: The state (probably RI)
        zipcode: The zipcode to look up
        smartystreets_auth_id: Your SmartyStreets auth_id
        smartystreets_auth_token: Your SmartyStreets auth_token
  Returns:
      The result if we find one, else None
  """
    # Authenticate to SmartyStreets API
    [
        _, street, state, zipcode, smartystreets_auth_id,
        smartystreets_auth_token
    ] = flat_address_list
    credentials = StaticCredentials(smartystreets_auth_id,
                                    smartystreets_auth_token)
    client = ClientBuilder(credentials).build_us_street_api_client()

    # Lookup the Address with inputs by indexing from input `row`
    lookup = StreetLookup()
    lookup.street = street
    lookup.state = state
    lookup.zipcode = zipcode

    lookup.candidates = 1
    lookup.match = "invalid"  # "invalid" always returns at least one match

    try:
        client.send_lookup(lookup)
    except exceptions.SmartyException:
        return None

    res = lookup.result
    if not res:
        # if we have exceptions, just return the inputs to retry later
        return None

    result = res[0]
    return SmartyStreetResult.from_metadata(result)
示例#19
0
    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
示例#20
0
def address_lookup_by_string(address_string):
    lookup = Lookup()
    lookup.street = address_string
    return address_lookup(lookup)
示例#21
0
def run():


    auth_id = context.get_context("auth_id")
    auth_token = context.get_context("auth_token")

    # 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)

    # The appropriate license values to be used for you subscriptions
    # can be found on the Subscriptions page of the account dashboard.
    # https://www.smartystreets.com/docs/cloud/licensing
    client = ClientBuilder(credentials).with_licenses(["us-standard-cloud"]).build_us_street_api_client()
    # client = ClientBuilder(credentials).with_custom_header({'User-Agent': 'smartystreets ([email protected])', 'Content-Type': 'application/json'}).build_us_street_api_client()
    # client = ClientBuilder(credentials).with_proxy('localhost:8080', 'user', 'password').build_us_street_api_client()
    # Uncomment the line above to try it with a proxy instead

    # Documentation for input fields can be found at:
    # https://smartystreets.com/docs/us-street-api#input-fields

    lookup = StreetLookup()
    lookup.input_id = "24601"  # Optional ID from your system
    lookup.addressee = "John Doe"
    lookup.street = "1600 Amphitheatre Pkwy"
    lookup.street2 = "closet under the stairs"
    lookup.secondary = "APT 2"
    lookup.urbanization = ""  # Only applies to Puerto Rico addresses
    lookup.city = "Mountain View"
    lookup.state = "CA"
    lookup.zipcode = "94043"
    lookup.candidates = 3
    lookup.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.

    try:
        client.send_lookup(lookup)
    except exceptions.SmartyException as err:
        print(err)
        return

    result = lookup.result

    if not result:
        print("No candidates. This means the address is not valid.")
        return

    first_candidate = result[0]

    print("Address is valid. (There is at least one candidate)\n")
    #print("Address = ", json.dumps(first_candidate.components))
    print("ZIP Code: " + first_candidate.components.zipcode)
    print("County: " + first_candidate.metadata.county_name)
    print("Latitude: {}".format(first_candidate.metadata.latitude))
    print("Longitude: {}".format(first_candidate.metadata.longitude))
    # print("Precision: {}".format(first_candidate.metadata.precision))
    # print("Residential: {}".format(first_candidate.metadata.rdi))
    # print("Vacant: {}".format(first_candidate.analysis.dpv_vacant))
    # Complete list of output fields is available here:  https://smartystreets.com/docs/cloud/us-street-api#http-response-output

    sm = SmartyStreetsAdaptor(result)
    res = sm.to_json()
    print("All fields  = \n", json.dumps(res, indent=2, default=str))
    def test_freeform_assigned_to_street_field(self):
        lookup = Lookup("freeform address")

        self.assertEqual("freeform address", lookup.street)
示例#23
0
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)

    # The appropriate license values to be used for you subscriptions
    # can be found on the Subscriptions page of the account dashboard.
    # https://www.smartystreets.com/docs/cloud/licensing
    client = ClientBuilder(credentials).with_licenses(
        ["us-core-cloud"]).build_us_street_api_client()
    # client = ClientBuilder(credentials).with_custom_header({'User-Agent': 'smartystreets ([email protected])', 'Content-Type': 'application/json'}).build_us_street_api_client()
    # client = ClientBuilder(credentials).with_proxy('localhost:8080', 'user', 'password').build_us_street_api_client()
    # Uncomment the line above to try it with a proxy instead

    # Documentation for input fields can be found at:
    # https://smartystreets.com/docs/us-street-api#input-fields

    lookup = StreetLookup()
    lookup.input_id = "24601"  # Optional ID from your system
    lookup.addressee = "John Doe"
    lookup.street = "1600 Amphitheatre Pkwy"
    lookup.street2 = "closet under the stairs"
    lookup.secondary = "APT 2"
    lookup.urbanization = ""  # Only applies to Puerto Rico addresses
    lookup.city = "Mountain View"
    lookup.state = "CA"
    lookup.zipcode = "94043"
    lookup.candidates = 3
    lookup.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.

    try:
        client.send_lookup(lookup)
    except exceptions.SmartyException as err:
        print(err)
        return

    result = lookup.result

    if not result:
        print("No candidates. This means the address is not valid.")
        return

    first_candidate = result[0]

    print("There is at least one candidate.")
    print("If the match parameter is set to STRICT, the address is valid.")
    print(
        "Otherwise, check the Analysis output fields to see if the address is valid.\n"
    )
    print("ZIP Code: " + first_candidate.components.zipcode)
    print("County: " + first_candidate.metadata.county_name)
    print("Latitude: {}".format(first_candidate.metadata.latitude))
    print("Longitude: {}".format(first_candidate.metadata.longitude))
示例#24
0
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()
    # client = ClientBuilder(credentials).with_proxy('localhost:8080', 'user', 'password').build_us_street_api_client()
    # Uncomment the line above to try it with a proxy instead

    # Documentation for input fields can be found at:
    # https://smartystreets.com/docs/us-street-api#input-fields

    lookup = Lookup()
    lookup.input_id = "24601"  # Optional ID from your system
    lookup.addressee = "John Doe"
    lookup.street = "1600 Amphitheatre Pkwy"
    lookup.street2 = "closet under the stairs"
    lookup.secondary = "APT 2"
    lookup.urbanization = ""  # Only applies to Puerto Rico addresses
    lookup.city = "Mountain View"
    lookup.state = "CA"
    lookup.zipcode = "94043"
    lookup.candidates = 3
    lookup.match = "Invalid"  # "invalid" is the most permissive match

    try:
        client.send_lookup(lookup)
    except exceptions.SmartyException as err:
        print(err)
        return

    result = lookup.result

    if not result:
        print("No candidates. This means the address is not valid.")
        return

    first_candidate = result[0]

    print("Address is valid. (There is at least one candidate)\n")
    print("ZIP Code: " + first_candidate.components.zipcode)
    print("County: " + first_candidate.metadata.county_name)
    print("Latitude: {}".format(first_candidate.metadata.latitude))
    print("Longitude: {}".format(first_candidate.metadata.longitude))
    def test_raises_exception_when_response_has_error(self):
        exception = exceptions.BadCredentialsError
        client = Client(MockExceptionSender(exception), FakeSerializer(None))

        self.assertRaises(exception, client.send_lookup, Lookup())
    def test_single_lookup_values_correctly_assigned_to_parameters(self):
        sender = RequestCapturingSender()
        serializer = FakeDeserializer({})
        client = Client(sender, serializer)
        lookup = Lookup()

        lookup.street = '0'
        lookup.street2 = '1'
        lookup.secondary = '2'
        lookup.city = '3'
        lookup.state = '4'
        lookup.zipcode = '5'
        lookup.lastline = '6'
        lookup.addressee = '7'
        lookup.urbanization = '8'
        lookup.match = match_type.INVALID
        lookup.candidates = '9'

        client.send_lookup(lookup)

        self.assertEqual('0', sender.request.parameters['street'])
        self.assertEqual('1', sender.request.parameters['street2'])
        self.assertEqual('2', sender.request.parameters['secondary'])
        self.assertEqual('3', sender.request.parameters['city'])
        self.assertEqual('4', sender.request.parameters['state'])
        self.assertEqual('5', sender.request.parameters['zipcode'])
        self.assertEqual('6', sender.request.parameters['lastline'])
        self.assertEqual('7', sender.request.parameters['addressee'])
        self.assertEqual('8', sender.request.parameters['urbanization'])
        self.assertEqual(match_type.INVALID,
                         sender.request.parameters['match'])
        self.assertEqual('9', sender.request.parameters['candidates'])
示例#27
0
def address_validation():

    found = True
    # 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']
    session['shipping_fn'] = request.form['first_name']
    session['shipping_ln'] = request.form['last_name']
    input_address = {
        'street': request.form['street1'] + ' ' + request.form['street2'],
        'city': request.form['city'],
        'state': request.form['state'],
        'zip': request.form['zip_code']
    }

    credentials = StaticCredentials(auth_id, auth_token)

    client = ClientBuilder(credentials).build_us_street_api_client()
    # client = ClientBuilder(credentials).with_custom_header({'User-Agent': 'smartystreets ([email protected])', 'Content-Type': 'application/json'}).build_us_street_api_client()
    # client = ClientBuilder(credentials).with_proxy('localhost:8080', 'user', 'password').build_us_street_api_client()
    # Uncomment the line above to try it with a proxy instead

    # Documentation for input fields can be found at:
    # https://smartystreets.com/docs/us-street-api#input-fields

    lookup = Lookup()
    #lookup.input_id = "24601"  # Optional ID from your system
    lookup.addressee = request.form['first_name'] + ' ' + request.form[
        'last_name']
    lookup.street = request.form['street1']
    lookup.street2 = request.form['street2']
    #lookup.secondary = "APT 2"
    lookup.urbanization = ""  # Only applies to Puerto Rico addresses
    lookup.city = request.form['city']
    lookup.state = request.form['state']
    lookup.zipcode = request.form['zip_code']
    lookup.candidates = 3
    lookup.match = "Invalid"  # "invalid" is the most permissive match

    try:
        client.send_lookup(lookup)
    except exceptions.SmartyException as err:
        print(err)
        return

    result = lookup.result

    if not result:
        found = False
        print("No candidates. This means the address is not valid.")
        flash('Address is not valid. Please re-enter shipping information.')
        return render_template('partials/address.html', found=found)

    #for output example fields here https://smartystreets.com/docs/cloud/us-street-api#http-response-status
    first_candidate = result[0]

    print("Address is valid. (There is at least one candidate)\n")
    suggested_address_line1 = first_candidate.delivery_line_1
    suggested_address_line2 = first_candidate.components.city_name + ", " + first_candidate.components.state_abbreviation + " " + first_candidate.components.zipcode
    print(first_candidate.delivery_line_1)
    print(suggested_address_line1)
    print(first_candidate.components.city_name + ", " +
          first_candidate.components.state_abbreviation + " " +
          first_candidate.components.zipcode)
    return render_template('partials/address.html',
                           found=found,
                           suggested_address_line1=suggested_address_line1,
                           suggested_address_line2=suggested_address_line2,
                           input_address=input_address)
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(Lookup())
    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].match = "invalid"  # "invalid" is the most permissive match
    batch[0].candidates = 5

    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].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("")