Skip to content

Instantly share code, notes, and snippets.

@ewdurbin
Last active December 22, 2015 09:19
Show Gist options
  • Save ewdurbin/6450994 to your computer and use it in GitHub Desktop.
Save ewdurbin/6450994 to your computer and use it in GitHub Desktop.
decorator for a flask route to disable based on missing environment configuration
from flask import Blueprint, jsonify
from utils import env_check
import os
import hipchat
ANNOY_HIPCHAT_TOKEN = os.environ.get('ANNOY_HIPCHAT_TOKEN')
annoy = Blueprint('annoy', __name__)
#-------
# Routes
#-------
@annoy.route('/annoy/<channel>')
@env_check('ANNOY_HIPCHAT_TOKEN')
def annoy_route(channel):
"""Spam a particular room"""
hipchat_api = hipchat.HipChat(token=ANNOY_HIPCHAT_TOKEN)
hipchat_api.message_room(channel, 'Screamer', 'test', notify=True)
body = { "action": "message sent" }
return jsonify(body)
from flask import jsonify
import os
class env_check(object):
def __init__(self, env_var):
self.env_var = env_var
def __call__(self, f):
def g(*args, **kwargs):
error_message = "Not Implemented, %s not configured" % (self.env_var)
response = jsonify(error=error_message)
response.status_code = 501
return response
if os.environ.get(self.env_var):
return f
else:
print "%s not supplied, %s route disabled" % (self.env_var, f.__name__)
return g
from flask import Blueprint, jsonify
import os
import hipchat
ANNOY_HIPCHAT_TOKEN = os.environ.get('ANNOY_HIPCHAT_TOKEN')
annoy = Blueprint('annoy', __name__)
#-------
# Routes
#-------
if os.environ.get('ANNOY_HIPCHAT_TOKEN'):
@annoy.route('/annoy/<channel>')
def annoy_route(channel):
"""Spam a particular room"""
hipchat_api = hipchat.HipChat(token=ANNOY_HIPCHAT_TOKEN)
hipchat_api.message_room(channel, 'Screamer', 'test', notify=True)
body = { "action": "message sent" }
return jsonify(body)
else:
@annoy.route('/annoy/<channel>')
def annoy_route(channel):
error_message = "Not Implemented, ANNOY_HIPCHAT_TOKEN not configured"
response = jsonify(error=error_message)
response.status_code = 501
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment