开发者

Dynamic printing in web.py

开发者 https://www.devze.com 2023-03-21 05:02 出处:网络
I\'m shifting an application from cgi to web.py. I get results and print them dynamically with a simple prin开发者_StackOverflow社区t statement in cgi. So the results have been printed before the page

I'm shifting an application from cgi to web.py. I get results and print them dynamically with a simple prin开发者_StackOverflow社区t statement in cgi. So the results have been printed before the page has completed loading. In web.py, I have a return statement and can't figure out how I can achieve the same.

Sample cgi code:

print "<p><b>Displaying Search Results</b></p>"
print "<table>"
cmd = subprocess.Popen(["find", location ,"-name", fileName], stdout=subprocess.PIPE)
for line in cmd.stdout:
    tableData=line.rstrip("\n")
    tableRow="<tr><td>tableData</td></tr>"
    print tableRow
print "</table>"

The above code would print a row at a time as it is generated. How do I write the same for web.py???


Either use a string which you append to and finally return:

s = "My page with..."
s += "More data"
for y in x:
    s += "And this!"
return s

Or the ability to yield data, described in http://webpy.org/cookbook/streaming_large_files There are some gotchas, you have to set some headers and you can't mix return and yield since you make it a generator.

A part from setting the headers, you'd use: yield "Some more data", similar to print in your CGI-script.


Even though you can ease porting by replacing prints with concatenation and a single return, consider using a templating engine (web.py has a built-in templating engine named Templetor).

Separating the logic from the presentation allows you to change one of them without thinking of the other one more easily.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号