Python: CGI update webpage before script exit

拥有回忆 提交于 2020-01-14 02:29:05

问题


Okay here's my situation. I wrote a HTML form with a textarea that submits a POST request to my python script. I use cgi library to parse the textarea and split it into an array. I then process the items using a loop and print items as they're processed. It seems that even though I put the print statement in the loop it doesn't print until the entire process is completed and the script has exited. The html page also hangs until the process is finished.

I have tried to flush the buffer using the sys.std.flush() after each print statement however it did not help.

Take a look at my code below. All help will be highly appreciated.

Thanks in advance.

import cgi
import urllib2

form = cgi.FieldStorage()

h = str(form.getvalue('list'))

list = h.split('\r\n');
try:
    print "Content-Type: text/html\n\n"
    print "<head>"
    print "<title>Age</title>"
    print "</head>"
    print "<body>"
    for x in range(0, len(list)):
        print "List: %s" %list[x] + "</br>"
        sck = urllib2.urlopen("http://www.google.com/")
        data = sck.read()
        if len(data) > 0:
            print "Data collected<br />"
        sck.close
    print "</body>"
except Exception:
    pass


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Python Demo</title>
<style type="text/css">
    #form {
        width: 400px;
    }

    #form label {
        display: block;
    }

    #form textarea {
        width: 100%;
    }

    #form input {
        display: block;
        margin-top: 10px;
    }
</style>
</head>

<body>
<div id="form">
<form id="form1" name="form1" method="post" action="demo.py">
    <label for="list">List:</label>
    <textarea name="list" id="list" cols="50" rows="10"></textarea>
    <input type="submit" name="submit" id="submit" value="Submit" />
</form>
</div>
</body>
</html>

回答1:


see

http://docs.python.org/library/cgi.html#common-problems-and-solutions

It says most HTTP servers buffer the output of cgi scripts until completed.



来源:https://stackoverflow.com/questions/5227166/python-cgi-update-webpage-before-script-exit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!