Skip to content

Instantly share code, notes, and snippets.

@DazWorrall
Created July 26, 2012 07:54
Show Gist options
  • Save DazWorrall/3180841 to your computer and use it in GitHub Desktop.
Save DazWorrall/3180841 to your computer and use it in GitHub Desktop.
Flask maintenance mode
from flask import Flask, redirect, url_for, request
app = Flask(__name__)
is_maintenance_mode = True
# Always throw a 503 during maintenance: http://is.gd/DksGDm
@app.before_request
def check_for_maintenance():
if is_maintenance_mode and request.path != url_for('maintenance'):
return redirect(url_for('maintenance'))
# Or alternatively, dont redirect
# return 'Sorry, off for maintenance!', 503
@app.route('/')
def index():
return 'Hello!'
@app.route('/maintenance')
def maintenance():
return 'Sorry, off for maintenance!', 503
if __name__ == '__main__':
app.run()
@Pirata21
Copy link

Nice solution!, thanks :)

"if is_maintenance_mode and request.path != url_for('maintenance') and not 'static' in request.path "

With that, the site still showing all the styles and does not show the site as plain text

Best regards and thanks again

@EpocDotFr
Copy link

EpocDotFr commented Jul 16, 2016

Better solution IMHO:

from flask import Flask, abort
import os

app = Flask(__name__)

@app.before_request
def check_under_maintenance():
    if os.path.exists("maintenance"): # Check if a "maintenance" file exists (whatever it is empty or not)
        abort(503) # No need to worry about the current URL, redirection, etc

@app.route('/')
def index():
    return "This is Admiral Ackbar, over"

@app.errorhandler(503)
def error_503(error):
    return "It's a trap!", 503

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

@nupiter
Copy link

nupiter commented Oct 20, 2016

@app.before_request
def check_for_maintenance():
    rule = request.url_rule.rule
    if is_maintenance_mode and 'maintenance' not in rule: 
        return redirect(url_for('maintenance'))

Also works

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment