Unable to create database when running flask app
Question:
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 ?
Answers:
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.
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?
I have figured out the answer. Do export FLASK_APP=run.py
, then running flask --app run.py run
runs perfectly.
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 ?
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.
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?
I have figured out the answer. Do export FLASK_APP=run.py
, then running flask --app run.py run
runs perfectly.