I'm trying to load my database ONCE with SQLALchemy in a flask app. I thought i could add the records to the database by running a script from the terminal command, but it seems that i'm having difficulties executing the python script?
- Does initializing the app by running
export FLASK_APP=app/__init__.pythenflask runeven loads the database? - Does starting up the local server each time re
folder structure:
app
api
__init__.py
log.py
tasks
__init__.py
test.py
__init__.py
models.py
utils.py
app/api/log.py
from app import app
from app.models import Race, db
from app.utils import *
def historical_records():
df_races, df_circuits, constructors, df_drivers, df_results = extract_to_df_race('results', seasons, races_round)
# Check if row exists in table
exists = db.session.query(db.exists().scalar())
if exists is None:
df_races, df_circuits, constructors, df_drivers, df_results = extract_to_df_race('results', seasons, races_round)
save_races_to_db(df_races, db)
else:
print("The database already contains data of 2016 to current race")
def save_races_to_db(df_races, db):
for idx,row in df_races.iterrows():
r = Race()
r.url = df_races.loc[idx,"url"]
r.season = df_races.loc[idx,"season"]
r.raceName = df_races.loc[idx,"raceName"]
db.session.add(r)
try:
db.session.commit()
except Exception as e:
db.session.rollback()
print(str(e))
historical_records()
I activated the virtual environment, then executed python app/api/log.py but encountered this error:
File "app/api/log.py", line 1, in <module>
from app import app
ImportError: No module named app
Does initializing the app by running export FLASK_APP=app/__init__.py then flask run even loads the database?
from ... import modelsand remove thatfrom app import app.__init__.pyfile?db.session.query(db.exists().scalar())either fails with an error or checks ifNULLexists (not in a position to test exactly which of the two) and is not a useful check to make. It’s just an emptyEXISTSstatement.