开发者

Python CGI script - redirect doesn't always work

开发者 https://www.devze.com 2023-01-27 17:45 出处:网络
I\'m writing a small CGI script for an assignment (Python 2.4) that takes form data, runs a shell command with it, and then d开发者_JS百科isplays one or another version of its own page depending on wh

I'm writing a small CGI script for an assignment (Python 2.4) that takes form data, runs a shell command with it, and then d开发者_JS百科isplays one or another version of its own page depending on what it just did. E.g. if you add a comment, it reloads the "item" version of the page rather than the "list of all items" view, incorporating the new comment. There are several places in the program where it's supposed to reload itself. In one place it works and in one place it doesn't and I'm wracking my brain trying to see the difference.

if mode == "change":
    if newcomment != "":
        comment_command = "some shell command \"" + item + "\" " + comment
        os.system(comment_command)
    if rating != "":
        rate_command = "same command \"" + item + "\" " + rating
        os.system(rate_command)
 # this NEVER works!
    print "%s%s" % ("Location:http://blahblah/cgi-bin/myproject.cgi?item=", urllib.quote_plus(item)) 

elif mode == "newitem":
    add_command = "command \"" + newitem + "\""
    result = os.system(add_command)
    retcode = os.WEXITSTATUS(result)
    # redirect depending on results
    if retcode == 1:
        # this one always works!
        print "%s%s" % ("Location:http://blahblah/cgi-bin/myproject.cgi?item=", urllib.quote_plus(newitem))
    else:
        print("Location:http://blahblah/cgi-bin/myproject.cgi")

I hope this is enough of the code. I don't see why it works in one place and not another. I would assume that it's ignoring both redirects and "falling past" the attempt at a redirect, except that the ?item= version does work in one place. Is there something about os.system that I don't understand?


If your command os.system print anything, your Location header could be invalid.

  • Ensure that your os.system is not output anything
  • If it should, the Location header should be go Before any data print
  • prefer subprocess module instead of os.system :
    import subprocess;
    subprocess.Popen(command, shell=True).communicate()


Check and make sure you're really not outputting anything before the location header. If there's anything at all output before that, you're not going actually get the location header to do anything.

0

精彩评论

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

关注公众号