【问题标题】:Python: How to redirect from a Python CGI script to a PHP page and keep POST dataPython:如何从 Python CGI 脚本重定向到 PHP 页面并保留 POST 数据
【发布时间】:2014-09-30 15:05:02
【问题描述】:

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

我发现了这个:How to make python urllib2 follow redirect and keep post method,但我不明白我应该如何在我的代码中使用 urllib2.HTTPRedirectHandlerClass。

【问题讨论】:

    标签: python post cgi urllib2 url-redirection


    【解决方案1】:

    为什么不使用 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()
    

    作为参考,我使用了 pythons 文档中的想法:
    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

    【讨论】:

    • 我需要在浏览器中从我的脚本到 response_page.php 进行页面重定向,这段代码似乎只获取响应。
    • "redirect while using post" 是指使用您的帖子数据获取新页面,对吗?你的应用程序不是“浏览器”吗? (也许我没说对)
    • 我现在很困惑。所以,我有一个 upload.php 页面,它通过表单向我的脚本发送一些数据,然后我在后台处理数据,我想重定向到另一个 php 页面 response_page.php,它根据处理后的数据显示信息.
    • 哦好的,现在更清楚了。为此,我将尝试修复我的解决方案。我认为你也应该在问题中写下这个。
    猜你喜欢
    • 2014-09-29
    • 2011-02-13
    • 2020-05-31
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-08
    相关资源
    最近更新 更多