示例#1
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
示例#2
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()
def getZipCode(cityName, stateName):
    auth_id = "64c1b167-5f64-f1ab-0898-5a13c92e2359"
    auth_token = "WfTDEo4wyzYEaOeoe3FV"

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

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

    lookup = ZIPCodeLookup()
    lookup.input_id = "dfc33cb6-829e-4fea-aa1b-b6d6580f0817"  # Optional ID from your system
    lookup.city = cityName
    lookup.state = stateName

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

    result = lookup.result
    zipcodes = result.zipcodes
    cities = result.cities

    # for zipcode in zipcodes:
    #     print("\nZIP Code: " + zipcode.zipcode)

    return zipcodes
示例#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_autocomplete_api_client()
    lookup = Lookup('4770 Lincoln Ave O')

    client.send(lookup)

    print('*** Result with no filter ***')
    print()
    for suggestion in lookup.result:
        print(suggestion.text)

    lookup.add_state_filter('IL')
    lookup.max_suggestions = 5

    suggestions = client.send(
        lookup)  # The client will also return the suggestions directly

    print()
    print('*** Result with some filters ***')
    for suggestion in suggestions:
        print(suggestion.text)
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
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()

    lookup = Lookup()
    lookup.city = "Mountain View"
    lookup.state = "California"

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

    result = lookup.result
    zipcodes = result.zipcodes
    cities = result.cities

    for city in cities:
        print("\nCity: " + city.city)
        print("State: " + city.state)
        print("Mailable City: {}".format(city.mailable_city))

    for zipcode in zipcodes:
        print("\nZIP Code: " + zipcode.zipcode)
        print("Latitude: {}".format(zipcode.latitude))
        print("Longitude: {}".format(zipcode.longitude))
示例#7
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_international_street_api_client()

    lookup = Lookup("Rua Padre Antonio D'Angelo 121 Casa Verde, Sao Paulo", 'Brazil')
    lookup.geocode = True  # Must be expressly set to get latitude and longitude.

    candidates = client.send(lookup)  # The candidates are also stored in the lookup's 'result' field.

    first_candidate = candidates[0]
    print("Address is {}".format(first_candidate.analysis.verification_status))
    print("Address precision: {}\n".format(first_candidate.analysis.address_precision))

    print(u"First Line: {}".format(first_candidate.address1))
    print(u"Second Line: {}".format(first_candidate.address2))
    print(u"Third Line: {}".format(first_candidate.address3))
    print(u"Fourth Line: {}".format(first_candidate.address4))
    print("Latitude: {}".format(first_candidate.metadata.latitude))
    print("Longitude: {}".format(first_candidate.metadata.longitude))
示例#8
0
class AddressCorrecter:
    """ Validates and returns a corrected address.
    """
    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()

    def _lookup_one(self, address, city):
        self.lookup.street = address
        self.lookup.city = city
        self.lookup.state = "CA"
        try:
            self.client.send_lookup(self.lookup)
        except exceptions.SmartyException as err:
            print(err)
            return

        result = self.lookup.result

        if not result:
            # print("Address not valid.")
            return False

        first_candidate = result[0]
        return first_candidate.delivery_line_1


# if __name__ == "__main__":
#     ac = AddressCorrecter()
#     ac._lookup_one("528 Shorebird Cir #8204", "Redwood City")
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():
    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_reverse_geo_api_client()

    # Documentation for input fields can be found at:
    # https://smartystreets.com/docs/cloud/us-reverse-geo-api#http-input-fields

    lookup = Lookup(40.111111, -111.111111)

    results = client.send(lookup)
    result = results[0]

    coordinate = result.coordinate
    print("Latitude: {}".format(coordinate.latitude))
    print("Longitude: {}".format(coordinate.longitude))

    print("Distance: {}".format(result.distance))

    address = result.address
    print("Street: {}".format(address.street))
    print("City: {}".format(address.city))
    print("State Abbreviation: {}".format(address.state_abbreviation))
    print("ZIP Code: {}".format(address.zipcode))
    print("License: {}".format(coordinate.get_license()))
示例#11
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))
示例#13
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))
示例#14
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_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("***********************************")
示例#15
0
 def load_config(self, config_file):
     """Resonsible for loading configs and setting up client"""
     config = configparser.ConfigParser()
     config.read(config_file)
     auth_id = config.get('SMARTY STREETS', 'auth_id')
     auth_token = config.get('SMARTY STREETS', 'auth_token')
     api_credentials = StaticCredentials(auth_id, auth_token)
     self.client = ClientBuilder(
         api_credentials).build_us_street_api_client()
示例#16
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("")
示例#17
0
def autoCompleteSmartyAPI():
    addr = request.args.get("address")
    auth_id = "4db04845-3fbe-8b38-d005-5dc10f75a80b"
    auth_token = "pAKyFrPrrfishQdMPgzU"
    credentials = StaticCredentials(auth_id, auth_token)
    client = ClientBuilder(credentials).build_us_autocomplete_api_client()
    lookup = AutocompleteLookup(addr)
    client.send(lookup)
    local_res = []
    for suggestion in lookup.result:
        local_res.append(suggestion.text)
    return jsonify(local_res)
def run():
    # key = "Your SmartyStreets Key here"
    # hostname = "Your Hostname here"

    # We recommend storing your secret keys in environment variables instead---it's safer!
    key = os.environ['SMARTY_AUTH_WEB']
    hostname = os.environ['SMARTY_WEBSITE_DOMAIN']

    credentials = SharedCredentials(key, hostname)

    # auth_id = os.environ['SMARTY_AUTH_ID']
    # token = os.environ['SMARTY_AUTH_TOKEN']
    # credentials = StaticCredentials(auth_id, token)

    # The appropriate license values to be used for your 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-autocomplete-pro-cloud"]).build_us_autocomplete_pro_api_client()
    lookup = AutocompleteProLookup('1042 W Center')

    client.send(lookup)

    print('*** Result with no filter ***')
    print()
    for suggestion in lookup.result:
        print suggestion.street_line, suggestion.city, ",", suggestion.state

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

    lookup.add_state_filter('CO')
    lookup.add_state_filter('UT')
    lookup.add_city_filter('Denver')
    lookup.add_city_filter('Orem')
    lookup.add_state_preference('CO')
    lookup.add_state_preference('UT')
    lookup.add_city_preference('Denver')
    lookup.selected = '1042 W Center St Apt A (24) Orem UT 84057'
    lookup.max_results = 5
    lookup.prefer_geo = geolocation_type.NONE
    lookup.prefer_ratio = 33
    lookup.source = 'all'

    suggestions = client.send(
        lookup)  # The client will also return the suggestions directly

    print()
    print('*** Result with some filters ***')
    for suggestion in suggestions:
        print suggestion.street_line, suggestion.city, ",", suggestion.state
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 = Lookup()
    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')
示例#20
0
    def __init__(self, context):
        self._context = context
        self._auth_id = context['smarty_streets_id']
        self._auth_token = context['smarty_streets_token']

        # This set up the credentials for the SDK
        self._credentials = StaticCredentials(self._auth_id, self._auth_token)

        # We will use the SDK for looking up zipcodes.
        self._zip_client = ClientBuilder(self._credentials).build_us_zipcode_api_client()

        # I am going to use the "raw" rest API for address lookup to provide a comparison of
        # the two API approaches. Also, I should be getting the URL for the context.
        self._address_lookup_url = "https://us-street.api.smartystreets.com/street-address"
示例#21
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
示例#22
0
    def suggest_address(self, location):
        client = ClientBuilder(
            self.__credentials).build_us_autocomplete_api_client()
        lookup = auto_lookup(location['address'])
        lookup.add_state_filter(location['state'])
        lookup.max_suggestions = 9

        try:
            suggestions = client.send(lookup)

            return suggestions

        except:
            return ("No candidates found.")
示例#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)

    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))
示例#24
0
def address_auto_complete():
    auth_id = os.environ.get('smartystreets_id')
    auth_token = os.environ.get('smartystreets_token')
    credentials = StaticCredentials(auth_id, auth_token)
    client = ClientBuilder(credentials).build_us_autocomplete_api_client()
    if not request.args:
        return jsonify({'msg': 'Missing address'}), 400
    address = request.args.get('address')
    if not address:
        return jsonify({'msg': 'Missing address'}), 400
    lookup = AutocompleteLookup(address)
    client.send(lookup)
    return jsonify(
        {'suggestions':
         [suggestion.text for suggestion in lookup.result]}), 200
示例#25
0
    def __init__(self):
        context = {
            'smarty_streets_id': 'your id',
            'smarty_streets_token': 'your token',
            'aws_access_key_id': "your id",
            'aws_secret_access_key': "your_key"
        }

        self.dynamodb = boto3.client(
            'dynamodb',
            aws_access_key_id=context["aws_access_key_id"],
            aws_secret_access_key=context["aws_secret_access_key"],
            region_name="us-east-2")

        self._auth_id = context['smarty_streets_id']
        self._auth_token = context['smarty_streets_token']

        # This set up the credentials for the SDK
        self._credentials = StaticCredentials(self._auth_id, self._auth_token)

        # We will use the SDK for looking up zipcodes.
        self._zip_client = ClientBuilder(
            self._credentials).build_us_zipcode_api_client()

        # I am going to use the "raw" rest API for address lookup to provide a comparison of
        # the two API approaches. Also, I should be getting the URL for the context.
        self._address_lookup_url = "https://us-street.api.smartystreets.com/street-address"
示例#26
0
 def __init__(self):
     self.vocabulary = ['zip', 'zipcode', 'address', 'lot' ,'size', 'school', 'elementary', 'middle', 'high', 'price', 'cost', 'long', 'square foot','bedroom',
              'bath', 'bathroom', 'setback', 'offers', 'million', 'millions', 'mil', 'default', 'house']
     auth_id = "4bb0e1a6-e627-4dcc-bf61-18e8888c6997"
     auth_token = "KyWfET9otO2WvqV6c9zv"
     credentials = StaticCredentials(auth_id, auth_token)
     self.client = ClientBuilder(credentials).build_us_extract_api_client()
     self.lookup = ExtractLookup()
     self.lookup.aggressive = True
     self.lookup.addresses_have_line_breaks = False
     self.lookup.addresses_per_line = 1
     self.regex = re.compile(r"(\d{5}-\d{4}|\d{5})")
     self.onlystreet = re.compile(r"(\d+\s+[A-z]+\s+[A-z]+)")
     self.longest_first = sorted(self.vocabulary, key=len, reverse=True)
     self.p = re.compile(r'(?:{})'.format('|'.join(map(re.escape, self.longest_first))))
     logging.info("Extraction initialized...")
示例#27
0
def smartystreets_client_builder():
    """
    Returns a new :class:`smartystreets_python_sdk.ClientBuilder` using
    credentials from the required environment variables
    ``SMARTYSTREETS_AUTH_ID`` and ``SMARTYSTREETS_AUTH_TOKEN``.

    The environment variable ``SMARTYSTREETS_LICENSES`` can be used to
    explicitly specify a comma-separated list of one or more licenses to
    consider for the API request.  By default no licenses are specified.  See
    `<https://www.smartystreets.com/docs/cloud/licensing>`__ for more
    information on licensing.
    """
    auth_id = environ.get('SMARTYSTREETS_AUTH_ID')
    auth_token = environ.get('SMARTYSTREETS_AUTH_TOKEN')
    licenses = environ.get('SMARTYSTREETS_LICENSES', '').split(",")

    if not auth_id and not auth_token:
        raise Exception(
            "The environment variables SMARTYSTREETS_AUTH_ID and SMARTYSTREETS_AUTH_TOKEN are required."
        )
    elif not auth_id:
        raise Exception(
            "The environment variable SMARTYSTREETS_AUTH_ID is required.")
    elif not auth_token:
        raise Exception(
            "The environment variable SMARTYSTREETS_AUTH_TOKEN is required.")

    return ClientBuilder(StaticCredentials(auth_id,
                                           auth_token)).with_licenses(licenses)
示例#28
0
def suggestaddress():
    credentials = StaticCredentials(AUTH_ID, AUTH_TOKEN)

    client = ClientBuilder(credentials).build_us_autocomplete_api_client()
    streetName = json.loads(request.data.decode())['streetName']
    print(streetName)
    try:
        lookup = AutocompleteLookup(streetName)

        client.send(lookup)
        resp = []
        for suggestion in lookup.result:
            resp.append(suggestion.text)
        return Response(json.dumps(resp, default=str), status=200, content_type="text/json")
    except Exception as e:
        return Response(json.dumps([], default=str), status=200, content_type="text/json")
示例#29
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)
示例#30
0
def get_client():
    auth_id = "a3f33473-fc69-27c6-3e28-537ec873c146"
    auth_token = "DQrNt8KMeLn5f3PRn7wI"

    credentials = StaticCredentials(auth_id, auth_token)
    client = ClientBuilder(credentials).build_us_street_api_client()

    return client