SoccerFan
SoccerFan

Reputation: 45

Why do so many people put the app.run() in flask sites into a __name__ == "__main__" condition?

I know what if __name__ == "__main__" does and use it, but why do so many people and the documentation put the " app.run() " function of flask in this condition?

Upvotes: 0

Views: 811

Answers (2)

Xammax
Xammax

Reputation: 138

This will ensure that when this module is imported, it won't run the code within

if __name__ == "__main__":

Your name == "main" when you run the .py directly.

ex:

foo.py
        import bar
        print("This is foo file)

now the inverse:

bar.py
import foo

def main():
    print(This is bar file)
    print(__name__)

if __name__ == "__main__":
    main()

(running the bar.py file)

python bar.py

This is foo file
This is bar file
"__main__"

(running the foo.py file)


python foo.py

this is foo file

I know others will comment and provide a more thorough answer. But this is one way of looking at it.

Cheers.

Upvotes: 2

Bhagyajkumar Bijukumar
Bhagyajkumar Bijukumar

Reputation: 113

This is because there are certain situation where you have to access certain variables for example when you have a sqlalchemy database and If you want create tables. You have to do

from app import db

In such situation you app will run

Also when you move to production you don't need run and app is called from elsewhere if you add if __name__ == "__main__" part run will not be called unnecessarly.

Upvotes: 2

Related Questions