Package: humble-database
humble-databaseThis file will become your README and also the index of your
documentation.Installpipinstallhumble_databaseHow to useDatabase Exampleimportpandasaspdimportosfromsqlalchemyimporttextfromurllib.requestimporturlretrieveurlretrieve("http://2016.padjo.org/files/data/starterpack/census-acs-1year/acs-1-year-2015.sqlite",filename='acs.db')db=Database(drivername='sqlite',database='acs.db')db.query_to_df("select * from sqlite_schema").head(2)<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }.dataframe tbody tr th {
    vertical-align: top;
}

.dataframe thead th {
    text-align: right;
}</style>typenametbl_namerootpagesql0tablestatesstates2CREATE TABLE states (\n    year INTEGER , \n  ...1tablecongressional_districtscongressional_districts3CREATE TABLE congressional_districts (\n    ye...db.query_to_df("""select * from states limit 5""")<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }.dataframe tbody tr th {
    vertical-align: top;
}

.dataframe thead th {
    text-align: right;
}</style>yearnamegeo_idtotal_populationwhiteblackhispanicasianamerican_indianpacific_islanderother_racemedian_agetotal_householdsowner_occupied_homes_median_valueper_capita_incomemedian_household_incomebelow_poverty_lineforeign_born_populationstate02015Alabama04000US0148589793204076129668119287058918190692566559038.7184639013410044765447658760161699720112015Alaska04000US02738432452472247395182545753983006341220133.3250185259600733557335574532585440222015Arizona04000US046828065380226328271820984112109222761329963695137.42463008194300514925149211590439144000432015Arkansas04000US052978204217493446648620774341932182217551382637.9114466312070041995419955505081428410542015California04000US06391448181481512221928441518454554769581358661434088781336.212896357449100645006450058916781068833606db.query_to_records("select * from states limit 2",)[0]{'year': 2015, 'name': 'Alabama', 'geo_id': '04000US01', 'total_population': 4858979, 'white': 3204076, 'black': 1296681, 'hispanic': 192870, 'asian': 58918, 'american_indian': 19069, 'pacific_islander': 2566, 'other_race': 5590, 'median_age': 38.7, 'total_households': 1846390, 'owner_occupied_homes_median_value': 134100, 'per_capita_income': 44765, 'median_household_income': 44765, 'below_poverty_line': 876016, 'foreign_born_population': 169972, 'state': '01'}ORM ExampleSQL Alchemy ModelsfrompydanticimportBaseModel,computed_field,field_validator,ConfigDict,FieldfromsqlalchemyimportForeignKeyfromsqlalchemy.ormimportDeclarativeBase,Mapped,mapped_column,relationshipfromtypingimportListclassBase(DeclarativeBase):year:Mapped[int]name:Mapped[str]geo_id:Mapped[str]total_population:Mapped[int]white:Mapped[int]black:Mapped[int]hispanic:Mapped[int]asian:Mapped[int]american_indian:Mapped[int]pacific_islander:Mapped[int]other_race:Mapped[int]median_age:Mapped[int]total_households:Mapped[int]owner_occupied_homes_median_value:Mapped[int]per_capita_income:Mapped[int]median_household_income:Mapped[int]below_poverty_line:Mapped[int]foreign_born_population:Mapped[int]classState(Base):__tablename__='states'state:Mapped[str]=mapped_column(primary_key=True)total_population:Mapped[int]places:Mapped[List['Place']]=relationship(back_populates='state_')congressional_districts:Mapped[List['CongressionalDistrict']]=relationship(back_populates='state_')classPlace(Base):__tablename__='places'place:Mapped[str]=mapped_column(primary_key=True)total_population:Mapped[int]state:Mapped[str]=mapped_column(ForeignKey("states.state"))state_:Mapped['State']=relationship(back_populates='places')classCongressionalDistrict(Base):__tablename__='congressional_districts'congressional_district:Mapped[str]=mapped_column(primary_key=True)state:Mapped[str]=mapped_column(ForeignKey("states.state"))state_:Mapped['State']=relationship(back_populates='congressional_districts')withdb.session_scope()assession:s=session.query(State).first()print(s,'\n')forplaceins.places:print(place.name,'::',place.median_household_income)<__main__.State object> 

Birmingham city, Alabama :: 32378
Dothan city, Alabama :: 44208
Hoover city, Alabama :: 77365
Huntsville city, Alabama :: 46769
Mobile city, Alabama :: 38678
Montgomery city, Alabama :: 41836
Tuscaloosa city, Alabama :: 44125withdb.session_scope()assession:result=session.query(State).limit(7).all()forstateinresult:print(state.name,len(state.places),len(state.congressional_districts))Alabama 7 7
Alaska 1 1
Arizona 16 9
Arkansas 6 4
California 137 53
Colorado 16 7
Connecticut 8 5Pydantic ModelsclassACSBase(BaseModel):model_config=ConfigDict(from_attributes=True)year:int=Field()name:str=Field()geo_id:str=Field()total_population:Optional[int]=Field(None)white:Optional[int]=Field(None)black:Optional[int]=Field(None)hispanic:Optional[int]=Field(None)asian:Optional[int]=Field(None)american_indian:Optional[int]=Field(None)pacific_islander:Optional[int]=Field(None)other_race:Optional[int]=Field(None)median_age:float=Field()total_households:Optional[int]=Field(None)owner_occupied_homes_median_value:int=Field()per_capita_income:int=Field()median_household_income:int=Field()below_poverty_line:Optional[int]=Field(None)foreign_born_population:Optional[int]=Field(None)state:int=Field()classPlaceModel(ACSBase):"""A Model for a record from the 'places' table"""place:strclassCDModel(ACSBase):"""A Model for a record from the 'congressional_districts' table"""congressional_district:strclassStateModel(ACSBase):"""A Model for a record from the 'states' table"""places:List[PlaceModel]congressional_districts:List[CDModel]@computed_field(return_type=float,title='People per District',)defavg_people_per_cd(self)->float:returnsum([cd.total_populationforcdinself.congressional_districts])/len(self.congressional_districts)fromIPython.displayimportJSON# mode = serialization includes computed fieldsJSON(StateModel.model_json_schema(mode='serialization'))<IPython.core.display.JSON object>fromhumble_database.data_modelimportDataModelACSDataModel=DataModel[StateModel]JSON(ACSDataModel.model_json_schema(mode='serialization'))<IPython.core.display.JSON object>withdb.session_scope()assession:orm_result=session.query(State).all()result=ACSDataModel(data=orm_result)resulttitle: DataModel[StateModel]description: NoneDataFrame:<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }.dataframe tbody tr th {
    vertical-align: top;
}

.dataframe thead th {
    text-align: right;
}</style>yearnamegeo_idtotal_populationwhiteblackhispanicasianamerican_indianpacific_islander...total_householdsowner_occupied_homes_median_valueper_capita_incomemedian_household_incomebelow_poverty_lineforeign_born_populationstateplacescongressional_districtsavg_people_per_cd02015Alabama04000US0148589793204076129668119287058918190692566...18463901341004476544765876016.0169972.01[{'year': 2015, 'name': 'Birmingham city, Alab...[{'year': 2015, 'name': 'Congressional Distric...694139.85714312015Alaska04000US02738432452472247395182545753983006341...250185259600733557335574532.058544.02[{'year': 2015, 'name': 'Anchorage municipalit...[{'year': 2015, 'name': 'Congressional Distric...738432.00000022015Arizona04000US046828065380226328271820984112109222761329963...246300819430051492514921159043.0914400.04[{'year': 2015, 'name': 'Avondale city, Arizon...[{'year': 2015, 'name': 'Congressional Distric...711564.77777832015Arkansas04000US052978204217493446648620774341932182217551...11446631207004199541995550508.0142841.05[{'year': 2015, 'name': 'Fayetteville city, Ar...[{'year': 2015, 'name': 'Congressional Distric...695398.75000042015California04000US0639144818148151222192844151845455476958135866143408...1289635744910064500645005891678.010688336.06[{'year': 2015, 'name': 'Alameda city, Califor...[{'year': 2015, 'name': 'Congressional Distric...735426.8113215 rows × 22 columns