Mike
Mike

Reputation: 779

Flask setup code run once, but not during tests

I have setup code in my Flask app that initializes some database entries in Mongo and schedules cron jobs. How do I have this run once when the server starts but not when I run tests?

My project is structured as:

/crypto
    __init__.py
    main.py
    /templates
    /statis
    /tests
        tests.py

where the app object and setup code is in main.py and looks like

app = Flask(__name__)

...

with app.app_context():

    # do database setup

    # do cron job setup

My test.py needs to run from crypto import main to access the app object but the act of importing it also runs the setup code, which I do not want. Is there something I'm missing structurally here that would solve this?


@Hi I'm Frogatto, I tried adding if __name__ == "__main__": around the setup code, however then that code doesn't run when I start the server locally with flask run.

Upvotes: 1

Views: 274

Answers (1)

frogatto
frogatto

Reputation: 29285

When Python interpreter reads a .py file (for example when you import it), it will execute all of its code forthwith. So, in order to execute a piece of code when that .py file is the main module of the program, you would need to put your setup code in the body of the following if:

if __name__ == "__main__":
    # setup here.

This if ensures that your setup code runs when that .py file is the main module to run.

Upvotes: 1

Related Questions