无法在运行Flask应用程序时创建数据库

huangapple go评论56阅读模式
英文:

Unable to create database when running flask app

问题

当我调用 python run.py 时,db.create_all() 函数会执行。但是当我调用 flask --app market runflask --app run.py run 时,db.create_all() 不会执行。请解释为什么会发生这种情况?

英文:

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 ?

答案1

得分: 2

当你运行python run.py时,run.py内部的__name__的值是__main__。这就是为什么if __name__ == "__main__"条件成立,然后执行db.create_all()

当你不直接执行你的主脚本,而是使用flask命令行工具来运行时,run.py文件中的__name__的值等于你的文件名。因此,你的条件为假,db.create_all()不会被执行。

此外,__name__是Python中的一个特殊内置变量,它提供了当前模块的名称。查看这个答案以了解更多信息:https://stackoverflow.com/questions/419163/what-does-if-name-main-do

英文:

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 https://stackoverflow.com/questions/419163/what-does-if-name-main-do

答案2

得分: 2

我已找到答案。执行FLASK_APP=run.py导出,然后运行flask --app run.py run即可正常运行。

英文:

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

答案3

得分: 1

flask --app run.py run不会执行ifmain块的内容,包括db.create_all()

您可以/应该将with app.app_context(): db.create_all()移出ifmain。

英文:

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.

huangapple
  • 本文由 发表于 2023年2月10日 15:27:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75408055.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定