3

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

Deepak
  • 2,487
  • 3
  • 21
  • 27
  • For debugging I'd do a `print args` right after parsing. If that is correct, and doesn't repeat, it rules out any `argparse` issues. – hpaulj Nov 03 '15 at 10:36
  • yeah, no issues there, i am getting all args.. :| – Deepak Nov 03 '15 at 10:51
  • Some servers restart after an application is edited. – hpaulj Nov 03 '15 at 10:58
  • When you run Flask with the reloader, [it runs twice](http://stackoverflow.com/questions/25504149/why-does-running-the-flask-dev-server-run-itself-twice). – dirn Nov 03 '15 at 12:11

1 Answers1

2

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.

Morreski
  • 302
  • 1
  • 5
  • you are right about using `if __name__...` line but i am not importing run.py anywhere, i mentioned in the ques, and i don't see any reason why would this be a reason for function being called twice. Also, i checked, it doesn't solve my problem. – Deepak Nov 03 '15 at 10:47
  • It could have been that because as it is said in this thread: That's how python works: http://stackoverflow.com/questions/6523791/why-is-python-running-my-module-when-i-import-it-and-how-do-i-stop-it – Morreski Nov 03 '15 at 11:05