4

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__.py then flask run even 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?

3
  • Your app is not a python file, how could you import it. You may try sth like from ... import models and remove that from app import app. Commented Aug 16, 2018 at 3:28
  • 1
    What's in your __init__.py file? Commented Aug 16, 2018 at 16:38
  • db.session.query(db.exists().scalar()) either fails with an error or checks if NULL exists (not in a position to test exactly which of the two) and is not a useful check to make. It’s just an empty EXISTS statement. Commented Aug 19, 2018 at 13:45

1 Answer 1

4
+25

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.