Deepak
Deepak

Reputation: 2727

using argparse to start flask server

I have created a flask application and want to run the server($ python run.py ) but before that want to do some basic db tasks on running $ python run.py --init

Code (run.py):

def init():
    do_dbstuff()
    start_server()

def do_dbstuff():
    # doing db stuff

def start_server():
    app.run(host='127.0.0.1', port=8080, debug=True)

parser = argparse.ArgumentParser(description="Welcome to my server", prog="Simpleserver")

parser.add_argument('--init', dest='run_init', action='store_true', help="does db stuff and starts the server")
parser.add_argument('--dbstuff', dest='run_do_dbstuff', action='store_true', help="does db stuff")

args = parser.parse_args()

if args.run_init:
    init()
elif args.run_do_db_stuff:
    do_dbstuff()
else:
    start_server()

Above code works, but the problem is when the server gets started init() function is called again( want it to run only once).

Why is that happening?

Thanks

Upvotes: 3

Views: 5017

Answers (1)

Morreski
Morreski

Reputation: 322

Isn't your script lacking something like this:

if __name__ == "__main__":
    args = parser.parse_args()
    if args.run_init:
        init()
    elif args.run_do_db_stuff:
        do_dbstuff()
    else:
        start_server()

IMHO you have another python file that is importing "run.py" and this is why your function is run twice. Remember that python code is executed when imported as a module.

Upvotes: 2

Related Questions