doyz
doyz

Reputation: 886

Flask + SQLAlchemy: Load database with records by running python script

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?

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?

Upvotes: 4

Views: 1909

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121594

Your issue is that you are using a module inside a package as a script; at that point the top-level module import path is set to the app/api/ directory. At the very least you’d run it as python -m app.api.log to keep the right context.

However, you should instead make your script a Flask command, because that gives you an an active application context.

Make your historical_records() function the command:

import click

from app import app
from app.models import Race, db
from app.utils  import * 

@app.cli.command()
def historical_records():
    # your function

Remove the historical_records() call from the end of the module.

You can then run the command with

FLASK_APP=app flask historical_records

(You don’t need to add /__init__.py to FLASK_APP)

We can’t tell you if flask run will load the database because we can’t see either __init__.py or db.py, nor do I know if you ran the create_all() function.

Upvotes: 4

Related Questions