0

I have been following a FLask/SQLalchemy tutorial over at talkpython, but I can't get SQLalchemy to create my SQLite database.

AT this moment I am in doubt if it's running the main method at all, int he terminal debug is set to 0 and the print statement from main() is never printed.

I really don't know what I have been doing wrong, the site lunches and I can browse it, but no SQLite file is ever created in the db folder.

app.py:

import os
import flask
import data.db_session as db_session

app = flask.Flask(__name__)


def main():
    print("print this if coming from main()")
    setup_db()
    app.run(debug=True)


def setup_db():
    db_file = os.path.join(
        os.path.dirname(__file__),
        'db',
        'database.sqlite')

    db_session.global_init(db_file)


@app.route('/')
def frontpage():
    return flask.render_template('index.html')


if __name__ == '__main__':
    main()

db_session.py:

import sqlalchemy as sa
import sqlalchemy.orm as orm

from data.modelbase import SqlAlchemyBase

factory = None


def global_init(db_file: str):
    global factory

    if factory:
        return

    if not db_file or not db_file.strip():
        raise Exception("You must specify a db file.")

    conn_str = 'sqlite:///' + db_file.strip()
    print("Connecting to DB with {}".format(conn_str))

    engine = sa.create_engine(conn_str, echo=False, connect_args={"check_same_thread": False})
    factory = orm.sessionmaker(bind=engine)

    # noinspection PyUnresolvedReferences
    from data.location import Location

    SqlAlchemyBase.metadata.create_all(engine)

Terminal output:

FLASK_APP = app.py
FLASK_ENV = development
FLASK_DEBUG = 0
In folder C:/Users/******/OneDrive/*********
"C:\Users\****\Anaconda3\envs\********\python.exe" -m flask run
 * Serving Flask app "app.py"
 * Environment: development
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

1 Answers1

0

To call your main method, you can initiate the app from the command line like this:

"C:\Users\****\Anaconda3\envs\********\python.exe" app.py

By doing this, your if __name__=="__main__" statement will evaluate to True and call your main() function.

Here's a helpful, relevant, but much longer, answer that relates to this which explains some of the complications with using this method to start your app.

captnsupremo
  • 689
  • 5
  • 11
  • Hi captnsupremo, thank you for taking the time to try and help me :) As it is now the website lunches as is, so I guess it probably reaches the app.run in some way? but I never see my print statement in main() printing nor do I see setup_db() creating any sqlite files in my db folder. and although debug is set to true, when the app is run it is set to 0 – user3573815 May 25 '20 at 17:58
  • Sort of right-- flask can launch your app without calling your main() function as long as you've created the app as you did in `app = flask.Flask(__name__)`. Here's a quickstart tutorial showing Flask doing that: https://flask.palletsprojects.com/en/1.1.x/quickstart/ In this case, Flask is never running your `app.run()` line or even your `main` function. In order for flask to actually run your main() function, you'll want to start it with the python interpreter, as mentioned above. – captnsupremo May 25 '20 at 18:11
  • @captnsupremo Thank you, you are a saint. I still don't quite get why it works that way, but now the print is printing and the database is connecting. But I guess that means that this whole way of doing stuff in pycharm is silly or ? do you by any chance know how to curcom went this, or how to get pycharm setup so I can just use the green run arrow in pycharm? Thank you so much for your help, I have been sitting with this problem most of the day today – user3573815 May 25 '20 at 18:28
  • Sorry your day was lost! I don’t have any experience with pycharm. If you move the setup_db() function call into the global namespace (I.e., just pull it outside the main() function), then you should be able to use your original ‘python -m flask run’ command and it will still execute your script, calling the setup_db(). I don’t know if that’s what you’re trying for, though. – captnsupremo May 26 '20 at 02:53