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



我有一个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。

为什么不使用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 apt:
https://twistedmatrix.com/

编辑:

在更好地理解你的要求之后,我发现这篇文章提到重定向307正是你想要的(如果现在我理解正确的话):

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

最新更新