def _create_county(self, row): county_name_info = [ item.strip() for item in row["county_name"].split(",") ] county_name, state = county_name_info[0], county_name_info[1] existing_county = len( County.objects.filter(name=county_name, state=state)) > 1 if not existing_county: population = row["population"] county = County(name=county_name, state=state, population=population) county.save()
def add_new_county(self, name): if not isinstance(name, str): return {"error": "Invalid name found: " + str(name)} try: return return_county(County(name=name).save()) except: raise return {"error": "Creating new county failed"}
def test_save_county(self): '''Test if a new County is saved''' county = County.query.filter_by(name='Kisumu').first() self.assertIsNone(county) County(name='Kisumu').save() new_county = County.query.filter_by(name='Kisumu').first() self.assertEqual('Kisumu', new_county.name)
class CountyData(object): def __init__(self): self.county = County() def fetch_county(self, code): if not isinstance(code, int): return {"error": "Invalid code found :" + str(code)} return return_county(self.county.get_one(code)) def fetch_all_counties(self): return [return_county(county) for county in self.county.get_all()] def add_new_county(self, name): if not isinstance(name, str): return {"error": "Invalid name found: " + str(name)} try: return return_county(County(name=name).save()) except: raise return {"error": "Creating new county failed"} def update_county(self, code, name): if not isinstance(code, int): return {"error": "Invalid code found: " + str(code)} elif not isinstance(name, str): return {"error": "Invalid name found: " + str(name)} county = self.county.get_one(code) county.name = name if name != "" else county.name try: return return_county(county.update()) except: raise return {"error": "Updating county failed"} def delete_county(self, code): if not isinstance(code, int): return {"error": "Invalid code found: " + str(code)} self.county.get_one(code).delete()
def create_county(state, countyDict): countyName = countyDict['county'] countyCode = countyDict['county_code'] avgData = countyDict['avg_loan'] countyGeojson = create_geojsonfeature(countyDict['geojson']) county = County(countyName, countyCode, state, countyGeojson, avgData) db.session.add(county) db.session.commit() create_censustracts(county, countyDict['census_tracts'])
def setUp(self): db.create_all(app=self.app_t) self.http = self.create_app().test_client() # Create a new County county = County(name="Nakuru").save() county = County(name="Turkana").save() # create constituencies associated with Nakuru constituency1 = Constituency(name="Kongowea", county_code=county.code) constituency2 = Constituency(name="Nairobi", county_code=county.code) # create wards associated with Kongowea and Nairobi Ward(name="xxxxx", constituency_code=constituency1.code) Ward(name="yyyyyy", constituency_code=constituency1.code) Ward(name="Hurama", constituency_code=constituency2.code) Ward(name="Pangani", constituency_code=constituency2.code)
def __init__(self): self.county = County()
def populate(csv_path): """ This function is used for populating the application database with the data in the provided csv path. As of writing this, the function does Not handle re-seeding with an updated version of the same dataset. """ logger.info("Populating") # We will store our temporary models here to avoid duplications cities = {} counties = {} regions = {} # Each row seems to reflect a city, so we create a city for each row. with open(csv_path, 'r') as f: reader = csv.reader(f, delimiter=";") for index, row in enumerate(reader): if index == 0: headers = row continue # Convert the row into a more usable format row_dict = row_to_dict(headers, row) # Take some keys to be used as foreign keys county_code = str(row_dict["Code Département"]) region_code = str(row_dict["Code Région"]) city = City(code_insee=row_dict["Code INSEE"], population=row_dict["Population"], code_postal=row_dict["Code Postal"], name=row_dict["Commune"], area=row_dict["Superficie"], county_code=county_code) cities[city.code_insee] = city # If this county hasn't been encountered yet, we will create a model for it if not county_code in counties: county = County(code=county_code, name=row_dict["Département"], region_code=region_code) counties[county_code] = county # If this region hasn't been encountered yet, we will create a model for it if not region_code in regions: region = Region(code=region_code, name=row_dict["Région"]) regions[region_code] = region logger.info("There are %s cities", len(cities)) logger.info("There are %s counties", len(counties)) logger.info("There are %s regions", len(regions)) # We will use add_all for now, but it means we can't repopulate due to IntegrityErrors items = ([city for _, city in cities.items()] + [county for _, county in counties.items()] + [region for _, region in regions.items()]) db.session.add_all(items) try: db.session.commit() except exc.IntegrityError: logger.error( "Failed to add the resources to the database as some already exist" ) db.session.rollback()
def processSignup(): return ("Signups for Kohoutek 2021 are now closed", 422) if ("organisation" not in request.form) or (request.form["organisation"] not in ["scouting", "guiding" ]): return ( "You haven't let us know whether you're in Guiding or Scouting", 422) organisation = Organisation(request.form["organisation"]) if "county" not in request.form or request.form["county"] not in [ "avon", "bsg", "sn", "other", ]: return ("You need to select which County you're in", 422) county = County(request.form["county"]) if (county in [County.avon, County.bsg, County.sn] and ("district" not in request.form or request.form["district"] == "")) or (county == County.other and ((organisation == Organisation.scouting and ("district-name" not in request.form or request.form["district-name"] == "")) or (organisation == Organisation.guiding and ("division-name" not in request.form or request.form["division-name"] == "")))): return ( "You need to select your District/Division, or enter it's name", 422) if county in [County.avon, County.bsg, County.sn]: district = District.query.filter_by( id=request.form["district"]).first() if district.county != county: return ( "You need to select a District/Division that's in your chosen County", 422, ) else: district_id = district.id district_name = None else: district_id = None district_name = (request.form["district-name"] if organisation == Organisation.scouting else request.form["division-name"]) if organisation == Organisation.scouting and ( "group-name" not in request.form or request.form["group-name"] == ""): return ("You need to tell us the name of your Group", 422) if organisation == Organisation.guiding and ( "unit-name" not in request.form or request.form["unit-name"] == ""): return ("You need to tell us the name of your Unit", 422) group_name = (request.form["group-name"] if organisation == Organisation.scouting else request.form["unit-name"]) if "troop-name" not in request.form or request.form["troop-name"] == "": troop_name = None else: troop_name = request.form["troop-name"] if "contact-name" not in request.form or request.form["contact-name"] == "": return ("You need to provide a contact name", 422) if "contact-email" not in request.form or request.form[ "contact-email"] == "": return ("You need to provide a contact email address", 422) if ("confirm-email" not in request.form or request.form["confirm-email"] == "" or request.form["contact-email"].lower() != request.form["confirm-email"].lower()): return ("You need to confirm your email address", 422) contact_email = request.form["contact-email"].lower() existing_signup = Entry.query.filter_by( contact_email=contact_email).first() if existing_signup: return ("This email address has already been used to sign up a group", 422) if "rules" not in request.form or request.form["rules"] != "accepted": return ( "You need to confirm you have read and accept the competition rules", 422, ) try: e = Entry( contact_name=request.form["contact-name"], contact_email=contact_email, organisation=organisation, county=county, district_id=district_id, district_name=district_name, group_name=group_name, troop_name=troop_name, ) db.session.add(e) db.session.commit() e.sendConfirmationEmail() return ("OK", 200) except Exception as e: return (f"There was a problem processing the sign up - {e}", 422)