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

问题描述 投票:0回答:2

我正在尝试编写一个Python脚本,在pyscripts / find_match.py​​中处理从upload.php页面中的POST接收的数据,将其发送到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标头的信息,但我不知道如何使用它们。尝试使用

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

在HEAD标签中,但它不起作用。请帮忙。

python redirect cgi url-redirection http-redirect
2个回答
0
投票

我希望人们不要在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"

-1
投票

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

2)打印'错误'是个问题。 cgi scripts stdout是浏览器,“错误”这个词会有问题。

3)chmod 755脚本

我投掷的重定向比网页多,这是我使用的功能。

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

我不知道是否需要最后一个print语句,并且Connection close标头对于大多数客户端来说似乎是可选的,但我保留它,因为它应该在那里,我想。 RFC阅读倾向于让我睡觉。

当我第一次编写cgi脚本时,我不使用cgi.FieldStorage,我对值进行硬编码以便我可以在命令行上测试它,在我开始工作之后,我在具有硬编码值的浏览器中尝试它,当时这是我在cgi.FieldStorage中添加工作。

查看

import cgitb
cgitb.enable()

我知道这可能会加重,我一直在那里。祝好运。

© www.soinside.com 2019 - 2024. All rights reserved.