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 ./manage.py 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):
            self.content.append(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...

@print_http_response
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>
1<BR>
2<BR>
3<BR>