0

I'm new to flask and I got stuck into one thing. So I have run.py file inside it

from market import app
from market.models import db

if __name__ == "__main__":
    with app.app_context():
        db.create_all()

        app.run(debug=True)

so when I call python run.py the db.create_all() function works. But when I call flask --app market run or flask --app run.py run the db.create_all() doesn't get executed.

Please explain why this happens ?

Sins97
  • 155
  • 1
  • 7

3 Answers3

2

When you run python run.py, then the value of __name__ inside your run.py is __main__. That's why if __name__ == "__main__" condition satisfies and db.create_all() executed.

When you don't execute your main script directly but with flask cli, the value of the __name__ in run.py file is equal to your file name. So your if condition is false and db.create_all() is not executed.

In addition, __name__ is a special built-in variable in python that provides the name of the current module. Check this answer to learn more about it What does if __name__ == "__main__": do?

2

I have figured out the answer. Do export FLASK_APP=run.py , then running flask --app run.py run runs perfectly.

Sins97
  • 155
  • 1
  • 7
1

flask --app run.py run does not execute the contents of your ifmain block, including the db.create_all().

You can/should move the with app.app_context(): db.create_all() out of the ifmain.

ljmc
  • 4,830
  • 2
  • 7
  • 26