From ade2adc571f0c98927dc04ebc1b877be2f4c2cc4 Mon Sep 17 00:00:00 2001 From: Kenneth Reitz Date: Mon, 13 Jun 2011 13:51:29 -0400 Subject: [PATCH] new filters module --- httpbin/filters.py | 87 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 httpbin/filters.py diff --git a/httpbin/filters.py b/httpbin/filters.py new file mode 100644 index 0000000..8811277 --- /dev/null +++ b/httpbin/filters.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- + +""" +httpbin.filters +~~~~~~~~~~~~~~~ + +This module provides response filter decorators. +""" + +import gzip +import json as simplejson + +from cStringIO import StringIO +from decimal import Decimal +from time import time as now + + +from decorator import decorator +from flask import Flask, Response + + +app = Flask(__name__) + + +@decorator +def x_runtime(f, *args, **kwargs): + """X-Runtime Flask Response Decorator.""" + + _t0 = now() + r = f(*args, **kwargs) + _t1 = now() + r.headers['X-Runtime'] = '{0}s'.format(Decimal(str(_t1-_t0))) + + return r + + +@decorator +def json(f, *args, **kwargs): + """JSON Flask Response Decorator.""" + + data = f(*args, **kwargs) + + # we already have a formatted response, move along + if isinstance(data, Response): + return data + + dump = simplejson.dumps(data, sort_keys=True, indent=3) + + r = app.make_response(dump) + r.headers['Content-Type'] = 'application/json' + + + return r + + +@decorator +def gzip(f, *args, **kwargs): + """GZip Flask Response Decorator.""" + + + data = f(*args, **kwargs) + + if isinstance(data, Response): + content = data.data + else: + content = data + + gzip_buffer = StringIO() + gzip_file = gzip.GzipFile( + mode='wb', + compresslevel=4, + fileobj=gzip_buffer + ) + gzip_file.write(content) + gzip_file.close() + + gzip_data = gzip_buffer.getvalue() + + if isinstance(data, Response): + data.data = gzip_data + data.headers['Content-Encoding'] = 'gzip' + data.headers['Content-Length'] = str(len(data.data)) + + return data + + return gzip_data +