class Population: """ This object connects to the GreatSchools.org API and retrieves information about schools and GS ratings. See more information on: http://www.greatschools.org/api/docs/main.page """ def __init__(self, recreate=False): datamodel = Datamodel() self.table, self.table_config = datamodel.population() self.postgres = Postgresql(user_name='postgres', password='******', host='localhost', port='5432', db='TestProject') self.postgres.initialize_table(self.table, recreate=False, **self.table_config) self.googlegeo = GoogleGeo() # myan: only get major cities data once per request self.major_cities_postgres = Postgresql(user_name='postgres', password='******', host='localhost', port='5432', db='TestProject') self.major_cities = self.major_cities_postgres.get( "select * from TestMajorCities") self.all_states = self.major_cities['state'].values self.all_cities = self.major_cities['city'].values self.all_lats = self.major_cities['lat'].values self.all_lngs = self.major_cities['lng'].values self.all_population = self.major_cities['population'].values def run(self, **kwargs): # myan: seems python has a strange way of handling memory pointers when deleting elements from lists in a loop # therefore create a separate list tmp_results to hold all the results from API calls first and decide what to # include. results_df = pd.DataFrame( self._closest_city_population(self._geo_info(**kwargs))) existing_keys = self.postgres.get( "select place_id from {table};".format(table=self.table)) addition_results = results_df.loc[np.logical_not( results_df['place_id'].isin(existing_keys['place_id'].values))] addition_results.drop_duplicates(subset='place_id', inplace=True) if len(addition_results) > 0: self.postgres.put_dataframe(addition_results, self.table_config['fields_types'], table=self.table) return results_df def _geo_info(self, addresses=None, fields_to_get=('place_id', 'state', 'city', 'county', 'lat', 'lng')): """ Get geo info from Google API Args: addresses: list of addresses Returns: list of dict, [{field1:value1, field2:value2, ...}, {...]] Examples: p = Population() results = p._geo_info(address=['Houston,TX', 'Dallas, TX']) """ if fields_to_get is None: raise ValueError('Argument fields_to_get must not be None.') results = [] for entry in addresses: output = self.googlegeo.get(entry, fields_to_get=fields_to_get) output.update(address=str(entry)) if isinstance(entry, int): output.update(zip_code=entry) results.append(output) return results def _closest_city_population(self, tmp_results): for entry in tmp_results: is_curr_state = self.all_states == entry['state'] same_state_cities = self.all_cities[is_curr_state] # myan: use a simple squared distance between two points to simply get the minimum euc_distance = (self.all_lats[is_curr_state] - entry['lat'])**2 + ( self.all_lngs[is_curr_state] - entry['lng'])**2 closest_idx = euc_distance.argmin() # myan: once we locate the closest major city, we can then calculate the actual haversine distance haversine_distance = haversine( (self.all_lats[is_curr_state][closest_idx], self.all_lngs[is_curr_state][closest_idx]), (entry['lat'], entry['lng'])) if haversine_distance <= MAX_DISTANCE_KM: entry.update(closest_city=same_state_cities[closest_idx]) entry.update(closest_city_population=self. all_population[is_curr_state][closest_idx]) else: entry.update(closest_city='NULL') entry.update(closest_city_population='NULL') return tmp_results
class Population: """ This object connects to the GreatSchools.org API and retrieves information about schools and GS ratings. See more information on: http://www.greatschools.org/api/docs/main.page """ def __init__(self,recreate=False): datamodel = Datamodel() self.table, self.table_config = datamodel.population() self.postgres = Postgresql(user_name='postgres', password='******', host='localhost', port='5432', db='TestProject') self.postgres.initialize_table(self.table, recreate=False, **self.table_config) self.googlegeo = GoogleGeo() # myan: only get major cities data once per request self.major_cities_postgres = Postgresql(user_name='postgres', password='******', host='localhost', port='5432', db='TestProject') self.major_cities = self.major_cities_postgres.get("select * from TestMajorCities") self.all_states = self.major_cities['state'].values self.all_cities = self.major_cities['city'].values self.all_lats = self.major_cities['lat'].values self.all_lngs = self.major_cities['lng'].values self.all_population = self.major_cities['population'].values def run(self, **kwargs): # myan: seems python has a strange way of handling memory pointers when deleting elements from lists in a loop # therefore create a separate list tmp_results to hold all the results from API calls first and decide what to # include. results_df = pd.DataFrame(self._closest_city_population(self._geo_info(**kwargs))) existing_keys = self.postgres.get("select place_id from {table};".format(table=self.table)) addition_results = results_df.loc[np.logical_not(results_df['place_id'].isin(existing_keys['place_id'].values))] addition_results.drop_duplicates(subset='place_id', inplace=True) if len(addition_results) > 0: self.postgres.put_dataframe(addition_results, self.table_config['fields_types'], table=self.table) return results_df def _geo_info(self, addresses=None, fields_to_get=('place_id', 'state', 'city', 'county', 'lat', 'lng')): """ Get geo info from Google API Args: addresses: list of addresses Returns: list of dict, [{field1:value1, field2:value2, ...}, {...]] Examples: p = Population() results = p._geo_info(address=['Houston,TX', 'Dallas, TX']) """ if fields_to_get is None: raise ValueError('Argument fields_to_get must not be None.') results = [] for entry in addresses: output = self.googlegeo.get(entry, fields_to_get=fields_to_get) output.update(address=str(entry)) if isinstance(entry, int): output.update(zip_code=entry) results.append(output) return results def _closest_city_population(self, tmp_results): for entry in tmp_results: is_curr_state = self.all_states == entry['state'] same_state_cities = self.all_cities[is_curr_state] # myan: use a simple squared distance between two points to simply get the minimum euc_distance = (self.all_lats[is_curr_state] - entry['lat']) ** 2 + (self.all_lngs[is_curr_state] - entry['lng']) ** 2 closest_idx = euc_distance.argmin() # myan: once we locate the closest major city, we can then calculate the actual haversine distance haversine_distance = haversine((self.all_lats[is_curr_state][closest_idx], self.all_lngs[is_curr_state][closest_idx]), (entry['lat'], entry['lng'])) if haversine_distance <= MAX_DISTANCE_KM: entry.update(closest_city=same_state_cities[closest_idx]) entry.update(closest_city_population=self.all_population[is_curr_state][closest_idx]) else: entry.update(closest_city='NULL') entry.update(closest_city_population='NULL') return tmp_results
class GreatSchools: """ This object connects to the GreatSchools.org API and retrieves information about schools and GS ratings. See more information on: http://www.greatschools.org/api/docs/main.page """ def __init__(self, key=None): if key is None: self.api_key = _get_great_schools_api_key() else: self.api_key = key # myan: initialize postgresql datamodel = Datamodel() self.table, self.table_config = datamodel.great_schools() self.postgres = Postgresql(user_name='postgres', password='******', host='localhost', port='5432', db='TestProject') self.postgres.initialize_table(self.table, recreate=False, **self.table_config) def set_api_key(self, key=None): self.api_key = key def run(self, **kwargs): # myan: seems python has a strange way of handling memory pointers when deleting elements from lists in a loop # therefore create a separate list tmp_results to hold all the results from API calls first and decide what to # include. tmp_results = self._nearby_schools(**kwargs) results = [] existing_keys = self.postgres.get("select gsid from {table};".format(table=self.table)) for entry in tmp_results: if len(existing_keys) < 1 or entry['gsid'] not in existing_keys['gsid'].values: results.append(entry) self._push(results) return results def _push(self, data, batch_size=500): fields_list = list(self.table_config['fields_types'].keys()) fields_to_push = self.postgres.construct_db_field_string(fields_list) start_idx = 0 while start_idx < len(data): end_idx = min(len(data), start_idx + batch_size) values_to_insert = self.postgres.parse_values_list(data[start_idx:end_idx], self.table_config['fields_types'], fields_list) start_idx = end_idx self.postgres.put(self.table, fields=fields_to_push, values=values_to_insert) def _nearby_schools(self, state=None, zip_code=None, radius=5, limit=10): """ Gets a list of schools for a specified physical location (i.e. state + zip_code), within a certain radius Args: state: zip_code: radius: limit: Returns: list, [dict(gsId=int, name=string, gsRating=float), dict(...), ...] Examples: gs = GreatSchools(key='Your GS Key') results = gs._nearby_schools(state='TX', zip_code=75228, limit=2) # [{'gsId': '1769', 'gsRating': '3', 'name': 'Bryan Adams High School'}, {'gsId': '7566', 'name': 'White Rock Montessori School'}] """ self._check_key() url = "http://api.greatschools.org/schools/nearby?key={key}&state={state}&radius={radius}&zip={zip_code}&limit={limit}".format( key=self.api_key, state=state, zip_code=zip_code, radius=radius, limit=limit) results = self._run(url, key_string='school', result_fields=[(int, 'gsId'), (None, 'name'), (float, 'gsRating')], zip_code=zip_code, state=state) return results def _run(self, url, key_string="school", result_fields=None, zip_code=None, state=None): """ Generic method to extract data from API calls Args: url: string, the API call url to retrieve data key_string: string, the parent field in the XML file result_fields: list, [(func, field), ...] where func can be int, float etc. Returns: list, [dict(field_1=value_1, field_2=value2, ...), dict(...)] """ nearby = requests.get(url) results = [] for school in ElementTree.fromstring(nearby.content).findall(key_string): curr_result = dict(zip_code=zip_code, state=state) try: for (func, field) in result_fields: if func is None: curr_result[field.lower()] = school.find(field).text else: curr_result[field.lower()] = func(school.find(field).text) except: pass if curr_result: results.append(curr_result) return results def _check_key(self): if self.api_key is None: raise ValueError("Use .set_api_key() method to set Great School API Keys first.")