Python CGI:如何在处理POST数据后重定向到另一个页面

0 投票
2 回答
14504 浏览
提问于 2025-04-18 16:14

我正在尝试写一个Python脚本,放在pyscripts/find_match.py里,这个脚本的目的是处理从upload.php页面收到的数据,然后把这些数据发送到connect.php,最后再重定向到另一个PHP页面response.php,这个页面会根据我处理过的数据来显示信息,并且里面有一个

<?php include '/connect_database.php';?>

的代码行。

到目前为止,我已经能够获取POST信息,处理这些信息,并通过JSON格式发送到connect.php,但我还不能让find_match.py重定向到response.php。我的代码看起来是这样的:

在pyscripts/find_match.py中:

print "Content-type: text/html"
print
print "<html><head>"
print "</head><body>"
import cgi
import cgitb
cgitb.enable()

try:
    form = cgi.FieldStorage()
    fn = form.getvalue('picture_name')
    cat_id = form.getvalue('selected')
except KeyError:
    print 'error'
else:
    # code to process data here

    data_to_be_displayed = # data to be used in connect.php; it's an array of ids

    import httplib, json, urllib2
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    conn = httplib.HTTPConnection('192.168.56.101:80')
    #converting list to a json stream
    data_to_be_displayed = json.dumps(data_to_be_displayed, ensure_ascii = 'False')
    conn.request("POST", "/connect_database.php", data_to_be_displayed, headers)
    response = conn.getresponse()
    text = response.read()
    # print response.status, text
    conn.close()

    # WHAT I WANT TOT DO HERE
    if response.status == 200:
        redirect('/response.php')
print "</body></html>"

在response.php中:

<!DOCTYPE html>
<html>

<head>
    <title>Response Page</title>
</head>
<body>
        <div id="main">
            <?php include '/connect_database.php';?>
        </div>
</body>
</html>

我找到了一些关于urllib.HTTPRequestHandler类和Location头的信息,但我不知道怎么使用它们。我试着在HEAD标签中使用

<meta http-equiv="refresh" content="0;url=%s" />

,但没有效果。请帮帮我。

2 个回答

-1

1) shebang在哪里? (#!/usr/bin/env python)

2) print 'error' 是个问题。 cgi脚本的输出是浏览器, 输出'error'会造成麻烦。

3) 给脚本设置权限为755。

我处理重定向的次数比处理网页的次数还多,这里是我用的函数。

def togo(location):
    print "HTTP/1.1 302 Found"
    print "Location: ",location,"\r\n"
    print "Connection: close \r\n"
    print ""

我不确定最后的打印语句是否必要,连接关闭的头部对大多数客户端似乎是可选的,但我还是保留它,因为我觉得应该有这个。我看RFC文档的时候总是容易困。

当我第一次写cgi脚本时,我不使用cgi.FieldStorage,而是直接写死值,这样可以在命令行上测试,等这个能正常工作后,我再用这些写死的值在浏览器里测试,等这也没问题后,我才会加入cgi.FieldStorage。

可以看看

import cgitb
cgitb.enable()

我知道这可能让人很烦,我也经历过。 祝你好运。

1

我真希望人们在2014年不要再尝试写CGI程序了。

在一个普通的CGI应用中,如果你想要重定向(也就是让用户跳转到另一个页面),你只需要在输出中加上一个“Location:”的头部信息,后面跟上目标地址。不过,如果你在脚本的开头就已经关闭了头部信息,并且打印了一个空的HTML文档,那就不对了。这不仅会导致重定向失败,还会影响到你处理表单错误的方式,因为你已经关闭了HTML标签。

所以,应该这样开始你的脚本:

# No printing at the start!
import cgi
...

try:
    form = cgi.FieldStorage()
    fn = form.getvalue('picture_name')
    cat_id = form.getvalue('selected')
except KeyError:
    print "Content-type: text/html"
    print
    print "<html><body>error</body></html>"
else:
    ...
    if response.status == 200:
        print "Location: response.php"

撰写回答