Where to put the debug flag in flask applications


Question

Reading the flask documentation I see that there are two places where usually put the debug flag:

  • after the creation of the flask object

    app = Flask(__name__)
    app.debug = True
    
  • or by the run method

    app.run(host='0.0.0.0', debug = True)
    

In my project I have the app/init.py file:

    from flask import Flask
    app = Flask(__name__) 
    #app.debug = True       
    from app import views
    if app.debug == True:
       ...
       ...

And the run.py file:

from app import app
import os
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port, debug = True)

The problem that I see with the second option (by app.run) is that the True value won't be set until executing the run method. Because that, in my init.py file I will have the default value of app.debug (False). By the first option I don't have that problem.

Is the above right or is there anything that I don't see? What is then the best place to put the debug value regardless the application?

1
7
3/13/2013 8:59:18 PM

Accepted Answer

The docs say Both methods have the exact same effect., but they are referring to after the Flask app has actually been run.

http://flask.pocoo.org/docs/quickstart/#debug-mode

In the case you describe above, the best option would be to use the first method as you're checking app.debug's value before the app is run, but after it is defined and after app.debug is set.

With that in mind, as your app gets bigger, you might consider having a slightly more robust structure where you can define a config-$ENV.py file that has the debug flag set in it.

app/conf/config-dev.py

DEBUG = True
# ... other settings (e.g., log location, project root, etc)

app/conf/config-live.py

DEBUG = False
# ... other settings (e.g., log location, project root, etc)

app/conf/__init__.py

EMPTY FILE

app/__init__.py

from flask import Flask

def create_app(env='dev'):
    app = Flask(__name__)
    app.config.from_object('app.conf.config-%s' % env)

    if app.debug:
        print 'running in debug mode'
    else:
        print 'NOT running in debug mode'
    return app

This means you'll be able to immediately check whether or not your app is going to be run in debug mode, and when you run your app you can tell it which environment it is being run in, which will define whether or not debug is set to True or False.

run.py

from app import create_app
import os

port = int(os.environ.get('PORT', 5000))
app = create_app(env='dev') #Or pass 'live' to NOT be in debug mode
app.run(host='0.0.0.0', port=port)
11
3/14/2013 2:18:09 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon