Skip to content

Instantly share code, notes, and snippets.

@NorthIsUp
Created August 29, 2012 17:09
Show Gist options
  • Save NorthIsUp/3515719 to your computer and use it in GitHub Desktop.
Save NorthIsUp/3515719 to your computer and use it in GitHub Desktop.
flask helpers
"""
disqus.flask.helpers
~~~~~~~~~~~
:author: Adam Hitchcock
:copyright: (c) 2011 DISQUS, Inc.
:license: Apache License 2.0, see LICENSE for more details.
"""
from flask import current_app
from flask import request
from functools import wraps
from werkzeug.exceptions import Unauthorized
def matcher(referer, whitelist):
"""For regex based whitelists"""
for regex in whitelist:
m = regex.match(referer)
if m and m.groups():
return True
return False
### Authentication
def authenticated_by_origin_from_config(f):
@wraps(f)
def wrapper(*args, **kwargs):
origin = request.headers.get('Origin', '')
if origin not in current_app.config['ORIGIN_WHITELIST']:
return Unauthorized()
resp = f(*args, **kwargs)
resp.headers['Access-Control-Allow-Origin'] = origin
resp.headers['Access-Control-Allow-Methods'] = 'GET'
resp.headers['Access-Control-Max-Age'] = '21600'
return resp
return wrapper
### Authentication
def authenticated_by_origin(whitelist):
def decorate(f):
@wraps(f)
def wrapper(*args, **kwargs):
origin = request.headers.get('Origin', '')
if origin not in whitelist:
return Unauthorized()
resp = f(*args, **kwargs)
resp.headers['Access-Control-Allow-Origin'] = origin
resp.headers['Access-Control-Allow-Methods'] = 'GET'
resp.headers['Access-Control-Max-Age'] = '21600'
return resp
return wrapper
return decorate
def make_module(name, importable=False, **kwattrs):
"""
This can be used to make a single file blueprint, somewhat like this...
blueprint = Blueprint(__name__, 'bp')
@blueprint.route("/foo/bar")
def foo(*args):
pass
__views_attrs = { 'foo': foo, }
views = make_module("views", **__views_attrs)
"""
import sys
import imp
module = imp.new_module(name)
if importable:
sys.modules[name] = module
return module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment