Python CGI脚本 - 重定向不总是有效
我正在为一个作业写一个小的CGI脚本(使用Python 2.4),这个脚本会接收表单数据,然后用这些数据运行一个命令,最后根据刚刚执行的操作显示自己页面的不同版本。例如,如果你添加了一个评论,它会重新加载“项目”版本的页面,而不是“所有项目列表”的视图,并且会把新评论包含进去。程序中有几个地方需要重新加载自己。在一个地方可以正常工作,而在另一个地方却不行,我一直在想这两者之间有什么不同。
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")
我希望这段代码足够了。我不明白为什么在一个地方可以工作而在另一个地方不行。我本以为它会忽略所有的重定向,导致重定向的尝试失败,然而?item=版本
在一个地方却是可以工作的。我是不是对os.system有什么不理解的地方?
2 个回答
0
检查一下,确保在位置头部之前你真的没有输出任何东西。如果在那之前有任何输出,那么位置头部就不会起作用。
0
如果你的命令 os.system 打印了任何内容,那么你的 Location 头可能是无效的。
- 确保你的 os.system 没有输出任何内容
- 如果它需要输出,Location 头应该在任何数据打印之前设置
- 建议使用 subprocess 模块,而不是 os.system:
import subprocess; subprocess.Popen(command, shell=True).communicate()