24

I am trying to build y first webservice using Python Flask. I am not able to understand what does it mean for Flask to emit out Restarting with reloader, every time i run my app.

This is my code.

#!venv/bin/python
from flask import Flask
from flask import request


def buildCache():
    print 'Hello World'

buildCache()

app = Flask(__name__)


@app.route('/search')
def index():
    query = request.args.get('query','', type=str);
    return  query


if __name__ == '__main__':
    app.run(debug = True)

when i run it

venv/bin/python ./app.py
Hello World
 * Running on http://127.0.0.1:5000/
 * Restarting with reloader
Hello World

I dont understand why buildCache method is being called twice? It seems to be related to "Restarting with the reoloader', what does that mean? How do i make sure that buildCache is only executed once, before the server starts.

konquestor
  • 1,308
  • 3
  • 15
  • 29

2 Answers2

19

This "reloads" the code whenever you make a change so that you don't have to manually restart the app to see changes. It is quite useful when you're making frequent changes.

You can turn off reloading by setting the debug parameter to False.

app.run(debug=False)

"[If debug=True] the debugger will kick in when an unhandled exception occurs and the integrated server will automatically reload the application if changes in the code are detected."

Source: http://flask.pocoo.org/docs/0.10/api/#flask.Flask.debug

Muntaser Ahmed
  • 4,487
  • 1
  • 16
  • 17
  • 2
    but i do not make a code change, i a just running the program and it still calls my buildCache function twice, why is that? – konquestor Sep 15 '14 at 21:08
  • When you start the server with reloading, the first time it will do things twice, as if to test the reloading. My guess is this is done so that the application is in the same state as it will be after subsequent reloads, so there is no qualitative difference between the first run and the subsequent reloads. I don't know how to disable that. – Sergey Orshanskiy Oct 04 '14 at 22:31
4

From flask documentation:

If you enable debug support the server will reload itself on code changes, and it will also provide you with a helpful debugger if things go wrong.

See this.

Try start application and then do touch app.py, if debug mode will be enable server will reload application.

Slava Bacherikov
  • 1,983
  • 13
  • 15