1313# Invoke Flask magic
1414app = Flask (__name__ )
1515
16- # Configuration
16+ # App Configuration
1717app .config ['SECRET_KEY' ] = 'S_U_perS3crEt_KEY#9999'
1818
19- # SQLAlchemy minimal configuration
19+ # SQLAlchemy Configuration
2020app .config ['SQLALCHEMY_DATABASE_URI' ] = 'sqlite:///db.sqlite3'
2121app .config ['SQLALCHEMY_TRACK_MODIFICATIONS' ] = False
2222
23- # Construct the DB Object ( SQLAlchemy interface)
23+ # DB Object = SQLAlchemy interface
2424db = SQLAlchemy (app )
2525
26- # Store Titanic data
26+ # Define the storage
2727class Data (db .Model ):
2828
2929 passengerId = db .Column (db .Integer , primary_key = True )
@@ -33,6 +33,7 @@ class Data(db.Model):
3333 age = db .Column (db .Integer , default = - 1 )
3434 fare = db .Column (db .Float , default = - 1 )
3535
36+ # Table constructor - called by the custom command 'load_data'
3637 def __init__ (self , passengerId , name , survived , sex , age , fare ):
3738 self .passengerId = passengerId
3839 self .name = name
@@ -41,24 +42,24 @@ def __init__(self, passengerId, name, survived, sex, age, fare):
4142 self .age = age
4243 self .fare = fare
4344
45+ # The string representation of the class
4446 def __repr__ (self ):
4547 return str (self .passengerId ) + ' - ' + str (self .name )
4648
47- # Custom command
49+ # Define the custom command
4850@app .cli .command ("load-data" )
4951@click .argument ("fname" )
5052def load_data (fname ):
5153 ''' Load data from a CSV file '''
5254 print ('*** Load from file: ' + fname )
5355
54- #engine = create_engine( app.config['SQLALCHEMY_DATABASE_URI'], echo=True )
56+ # Build the Dataframe from pandas
5557 df = pd .read_csv ( fname )
56-
57- #df.to_sql(' data', con=engine)
58+
59+ # Iterate and load the data
5860 for row in df .itertuples (index = False ):
59-
61+
6062 print ( '************************************************' )
61- # print ( str(row[0]) + ' - ' + str(row[3]))
6263
6364 v_passengerId = row [0 ]
6465 v_survived = row [1 ]
@@ -81,20 +82,20 @@ def load_data(fname):
8182 # All good, commit changes
8283 db .session .commit ( )
8384
84- # Routes
85+ # Default Route
8586@app .route ('/' )
8687def hello_world ():
8788 retVal = 'Hello, the database has (' + str ( len (Data .query .all ()) )+ ') rows'
8889 retVal += '<br /> See loaded <a href="/data">data</a>.'
8990
9091 return retVal
9192
92- # Routes
93+ # Data Route - Shows the loaded information
9394@app .route ('/data' )
9495def data ():
9596
9697 retVal = 'Rows = ' + str ( len (Data .query .all ()) ) + '<br />'
9798
9899 for row in Data .query .all ():
99100 retVal += '<br />' + str ( row .__repr__ () )
100- return retVal
101+ return retVal
0 commit comments