2

Is there any function do the same result like PHP ob_start(myCallbackFunction) and ob_end_flush() that allow me modify the layouts and views in Python frameworks (Django/others)? thanks!

UPDATE

<?php
ob_start(function($res){
   echo str_replace('test','new string',$res);
});
?>

test
test
test
test

<?php ob_end_flush(); ?>
  • 1
    Can you expend on your intended use-case? While I can't think of a direct alternative, there's probably a more common django-ic way of achieving the same end result. – yuvi Mar 01 '14 at 19:49
  • Also, it seems you can use `yield` to emulate a buffer. See this: http://stackoverflow.com/questions/1371020/django-flush-response – yuvi Mar 01 '14 at 19:51
  • updated my question,I want to do something like that –  Mar 01 '14 at 20:31
  • 1
    Instead of posting PHP code, you should probably post the Python code where you need this, as you cannot really print responses piece by piece in Django as you do in PHP, and so your question does not make much sense. – lanzz Mar 01 '14 at 23:29

2 Answers2

2

To achieve this result in Python directly, you could patch stdout/stderr as discussed here;

Temporarily Redirect stdout/stderr

For Django templates, you'd just wrap your calls in a block (or a separate file) and include them where necessary.

It's worth mentioning that this approach is not not very pythonic, and you should think about what you're trying to do and find a more pythonic way to achieve it. If you tell us a bit more about your use case, we might be able to suggest a better way.

Community
  • 1
  • 1
SleepyCal
  • 5,739
  • 5
  • 33
  • 47
  • In my php code, every view and layouts has ob function for replacing string, e.g. some filter on web forum. And the ob functions will callback to a helper which control what string need to be replaced, I considering move to python but don't know how to achieve this –  Mar 02 '14 at 13:15
2

Let's implement PHP's ob_start and ob_get_contents functions in python3.

The outputs are being stored in a file, any type of stream could be used as well.

from functools import partial
output_buffer = None
print_orig = print
def ob_start(fname="print.txt"):
    global print
    global output_buffer
    print = partial(print_orig, file=output_buffer)
    output_buffer = open(fname, 'w')
def ob_end():
    global output_buffer
    close(output_buffer)
    print = print_orig
def ob_get_contents(fname="print.txt"):
    return open(fname, 'r').read()

Usage:

print ("Hi John")
ob_start()
print ("Hi John")
ob_end()
print (ob_get_contents().replace("Hi", "Bye"))

Would print

Hi John Bye John

Uri Goren
  • 13,386
  • 6
  • 58
  • 110