Skip to content

Instantly share code, notes, and snippets.

@jokull
Created March 26, 2012 16:03
Show Gist options
  • Save jokull/2206168 to your computer and use it in GitHub Desktop.
Save jokull/2206168 to your computer and use it in GitHub Desktop.
Flask base app.py
# encoding=utf-8
import datetime, locale
from functools import partial
from urllib import quote_plus
from raven.contrib.flask import Sentry
from redis import Redis
from flask import (Flask, g, url_for, render_template, request, jsonify, abort,
redirect)
from directoryhash import path_checksum
redis = Redis() # thread safe
try:
locale.setlocale(locale.LC_ALL, "is_IS.UTF-8") # To print nice dates
except:
pass
app = Flask(__name__)
app.config.update(
SECRET_KEY='`import os; os.urandom(20)`',
SENTRY_DSN='Get from sentry.com',
CDN=None,
)
sentry = Sentry(app)
@app.route('/')
def site():
return render_template('site.html')
def static(filename, _external=False):
"""If `CDN` config is defined we assume that static assets are being served
from a CDN or S3. We strip `/static` and serve from a versioned folder. Each
version is named after the MD5 hash of the public assets folder (see
directoryhash.py for impl of folder hashing). """
get_path = partial(url_for, 'static', filename=filename, _external=_external)
if app.config.get('CDN'):
return u'//{hostname}/{revision}{path}'.format(
hostname=app.config['CDN'], revision=g.revision, path=get_path())
return get_path(revision=g.revision)
@app.context_processor
def context():
return dict(
static = static,
)
@app.template_filter('urlquote')
def do_urlquote(s):
"""For whatever reason urllib isn't unicode safe. """
if isinstance(s, unicode):
s = s.encode(u'utf-8')
return quote_plus(s)
@app.before_request
def set_revision():
g.revision = redis.get(u'{}:revision'.format(app.import_name)) \
or path_checksum([app.static_folder])
app.route('/havoc')(lambda x: 1/0)
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment