def normalize_city_state(city=None, state=None): """ Utility function that accepts string representations of city and state, and returns a tuple of a validated city, state and zipcode value. :param city: Type: str Description: Name of a city to lookup. Default is None :param state: Type: str Description: Name or abbreviation of a US state to lookup. Default is None :return: Function accepts a city and state combination to lookup. The city and state combination is matched against a database of all US cities and states. If a valid match is found, a tuple with the city and state name are returned. If just one zipcode exists for that city and state combination, a zipcode is also returned. If multiple zipcodes match the city and state combination, then None is returned as the zipcode value in the tuple. The tuple is returned as ("cityname", "statename", "zipcode"). If lookup fails for one or all three items a None object is returned in the tuple. """ zipcode_search = ZipcodeSearchEngine() if state and city: try: city_state_zips = zipcode_search.by_city_and_state(city, state) if city_state_zips: zip_object = city_state_zips[0] single_zipcode = None if len(city_state_zips) == 1: single_zipcode = zip_object.Zipcode return zip_object.City, zip_object.State, single_zipcode except ValueError: return city, validate_state(state), None elif state: return None, validate_state(state), None
def zipFromCityState(city, state): """ :param city: :param state: :return: """ search = ZipcodeSearchEngine() return search.by_city_and_state(city, state)
def city_to_zipcodes(city, state): zipcodeEngineSearch = ZipcodeSearchEngine() try: zipcodes = zipcodeEngineSearch.by_city_and_state(city, state) if not zipcodes: # A zipcode that is known to return null return [zipcodeEngineSearch.by_zipcode(97003)] return zipcodes except ValueError: # A zipcode that is known to return null return [zipcodeEngineSearch.by_zipcode(97003)]
def _convert_zip(city, state, idx, errors): try: search = ZipcodeSearchEngine() result = search.by_city_and_state(city, state) zipcode = result[0]['Zipcode'] # print('Zipcode for {} , {} is: {}'.format(city, state, zipcode)) return zipcode, errors except: print( 'Error! Could not find city {} in state {} for id#: {}.'.format( city, state, idx)) zipcode = None errors[idx] = (city, state) return zipcode, errors
def new_item(request): if not request.user.is_authenticated: return redirect('/accounts/login') current_user = request.user e_user = ExtendedUser.objects.get(user=current_user) try: a_user = get_object_or_404(AdminUser, extended_user=e_user) except: return redirect('/home') if a_user.registered is not True: return redirect('/home') if request.method == 'POST': instance = Garbage(owner=a_user) form = GarbageAdd(request.POST, request.FILES, instance=instance) sendfrom = "new" if form.is_valid(): print("lalal") sendfrom = "new" instance.cost = form.cleaned_data['cost'] instance.title = form.cleaned_data['title'] instance.condition = form.cleaned_data['condition'] instance.description = form.cleaned_data['description'] instance.photos = form.cleaned_data['photos'] if (form.cleaned_data['Latitude'] == None or form.cleaned_data['Longitude'] == None): search = ZipcodeSearchEngine() res = search.by_city_and_state(e_user.city, e_user.state) instance.location = Point(res[0]["Latitude"], res[0]["Longitude"]) instance.latitude = res[0]["Latitude"] instance.longitude = res[0]["Longitude"] else: instance.location = Point(form.cleaned_data['Latitude'], form.cleaned_data['Longitude']) instance.latitude = instance.location.coords[0] instance.longitude = instance.location.coords[1] instance.city, instance.state = getplace(instance.latitude, instance.longitude, e_user.city, e_user.state) instance.save() message_type = True message = "Item created successfully." request.session['message'] = message request.session['message_type'] = message_type return redirect(sell) elif request.method == 'GET': form = GarbageAdd() sendfrom = "new" return render(request, "new_item.html", {'sendfrom': sendfrom})
def get_demo(**kwargs): print("in get_demo") print(kwargs) if("city" in kwargs and "state" in kwargs): city = kwargs['city'] state = kwargs['state'] else: city = "austin" state= "tx" print(city,state) zipSearch = ZipcodeSearchEngine() demoCall = zipSearch.by_city_and_state(city, state, returns=0, standard_only=False) # print(type(demoCall)) # demographics = json.dumps(demographics) # demographics = json.loads(demographics) print("0000000") # demographics = jsonify(demographics) features=[] for i in demoCall: feature={} zip_search = i.Zipcode population=i.Population income=i.Wealthy #query geocoordinates from the zip_shape table in the DB geometry=session.query(zip_shapes.geometry).filter(zip_shapes.zip_code==int(zip_search))[0][0] #pass the string of geocoordinates json.load start_index=geometry.find('[[') coordinate=json.loads(geometry[start_index:-1]) type_end=geometry.find("', 'coordinates") geo_type=geometry[10:type_end] #pull in information into one geoJSON feature feature={'type':'Feature',\ 'properties':{'zipcode':zip_search,'population':population,'income_per_capita':income},\ 'geometry':{'type':geo_type,'coordinates':coordinate}\ } #remove any postbox zipcode with a population with 0 if feature['properties']['population']==0: print('>>>>>>>>>>>>>>>>>> delete' + feature['properties']['zipcode']) else: features.append(feature) #put all the features in to a feature_collections object feature_collections={"type": "FeatureCollection","crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::4269" } },"name": "cb_2017_us_zcta510_500k","features":features} return feature_collections
def get_ziplist(**kwargs): print("in get_ziplist") print(kwargs) if("city" in kwargs and "state" in kwargs): city = kwargs['city'] state = kwargs['state'] else: city = "austin" state= "tx" print(city,state) ziplist = [] zipSearch = ZipcodeSearchEngine() zipCall = zipSearch.by_city_and_state(city=city, state=state, returns=0, standard_only=False) print(len(zipCall)) for i in zipCall: print(i.Zipcode) for i in zipCall: d = i.Zipcode ziplist.append(d) # print(demographics) print(ziplist) return ziplist
# define quandl api key API_KEY = "XL_c6FZRjuz6WYRTJB_a" # set cities to query cities_states = [ dict(state="Texas", city="Austin"), dict(state="Texas", city="Huston"), dict(state="Texas", city="Dallas") ] # get zip codes per query city df = pd.DataFrame() index = 0 for city_state in cities_states: zip_codes = search.by_city_and_state(state=city_state["state"], city=city_state["city"], returns=200) for zip_code in zip_codes: df = df.append(pd.DataFrame(zip_code.to_dict(), index=[index])) index += 1 zip_code = "78739" area_category = "Z" area_code = zip_code # set quandl api key quandl.ApiConfig.api_key = API_KEY # set the indicator code to query indicator_code = "ZHVIAH" # get quandl code to query