Python:如何从Python CGI脚本重定向到PHP页面并保持POST数据

0 投票
1 回答
978 浏览
提问于 2025-04-18 16:22

我有一个叫做upload.php的页面,它通过一个表单把一些数据发送给一个Python的CGI脚本。然后我在后台处理这些数据,最后想要跳转到另一个PHP页面response_page.php,这个页面会根据处理后的数据来显示信息。不过,我不能同时把数据发回PHP并进行跳转。

我的代码是:

#!/usr/bin/env python

import cgi
import cgitb
cgitb.enable()

try:
    form = cgi.FieldStorage()
    fn = form.getvalue('picture_name')
    cat_id = form.getvalue('selected')
except KeyError:
    print "Content-type: text/html"
    print
    print "<html><head>"
    print "</head><body>error</body></html>"
else:
    ...
    # here I processed the form data and stored it in data_to_be_displayed 
    # data to be processed and displayed in the response page
    data_to_be_displayed = [1,2,3]

    import httplib, json, urllib
    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')
    postData = urllib.urlencode({'matches':data_to_be_displayed})
    conn.request("POST", "/response_page.php", postData, headers)
    response = conn.getresponse()

    if response.status == 200:
        print "Location: /response_page.php"
        print # to end the CGI response headers.

    conn.close()

我找到了一些信息:如何让python urllib2跟随重定向并保持POST方法,但是我不太明白该如何在我的代码中使用urllib2.HTTPRedirectHandlerClass。

1 个回答

0

你为什么不使用liburl2来发送请求到response_page.php呢?

import urllib
import urllib2
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
data_to_be_displayed = json.dumps(data_to_be_displayed, ensure_ascii = 'False')
postData = urllib.urlencode({'matches':data_to_be_displayed})
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()

作为参考,我用了Python文档中的一个想法:
https://docs.python.org/2/howto/urllib2.html#headers

你也可以考虑使用Twisted这个库,它提供了更高级的代码:
https://twistedmatrix.com/

编辑:

在更好地理解你在问什么之后,我发现这个帖子提到的307重定向正是你想要的(如果我现在理解得没错的话):

https://softwareengineering.stackexchange.com/questions/99894/why-doesnt-http-have-post-redirect

撰写回答