Redirect console output to a Django HttpResponse

Say you have some Python code that prints to the console, and you want to re-use that code in a Django view, but output the print statements as HTML in the HttpResponse. Perhaps, like me, you have a batch job that you're calling from ./ script that you would also like to call from an HTTP request and see the results as text/HTML. Here is a decorator that does just that.

import sys
from django.http import HttpResponse

def print_http_response(f):
    """ Wraps a python function that prints to the console, and
    returns those results as a HttpResponse (HTML)"""

    class WritableObject:
        def __init__(self):
            self.content = []
        def write(self, string):

    def new_f(*args, **kwargs):
        printed = WritableObject()
        sys.stdout = printed
        f(*args, **kwargs)
        sys.stdout = sys.__stdout__
        return HttpResponse(['<BR>' if c == '\n' else c for c in printed.content ])
    return new_f

If you attached it like so to a view...

def my_view(request):
   print "some output here"
   for i in [1, 2, 3]:
      print i

It would output the following HTML:

some output here<BR>

I'm currently working at NerdWallet, a startup in San Francisco trying to bring clarity to all of life's financial decisions. We're hiring like crazy. Hit me up on Twitter, I would love to talk.

Follow @chase_seibert on Twitter