python - 如何从 python 返回 HTTP 303?

标签 python python-2.7 cgi http-status-codes http-status-code-303

这个问题来自this one .

我想要的是当用户单击按钮时能够从我的 python 脚本返回 HTTP 303 header 。我的脚本非常简单,就输出而言,它打印以下两行:

print "HTTP/1.1 303 See Other\n\n"
print "Location: http://192.168.1.109\n\n"

我还尝试了上述的许多不同变体(在行尾使用不同数量的 \r\n),但没有成功;到目前为止,我总是收到内部服务器错误

以上两行足以发送 HTTP 303 响应吗?还应该有别的吗?

最佳答案

假设您使用的是 cgi ( 2.7 )( 3.5 )

下面的示例应重定向到同一页面。该示例不会尝试解析 header ,检查发送的 POST 内容,它只是在检测到 POST 时重定向到页面 '/'

# python 3 import below:
# from http.server import HTTPServer, BaseHTTPRequestHandler
# python 2 import below:
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import cgi
#stuff ...
class WebServerHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        try:
            if self.path.endswith("/"):
                self.send_response(200)
                self.send_header('Content-type', 'text/html')
                self.end_headers()

                page ='''<html>
                         <body>
                         <form action="/" method="POST">
                         <input type="submit" value="Reload" >
                         </form>
                         </body>
                         </html'''

                self.wfile.write(page)
        except IOError:
            self.send_error(404, "File Not Found {}".format(self.path))
    def do_POST(self):
        self.send_response(303)
        self.send_header('Content-type', 'text/html')
        self.send_header('Location', '/') #This will navigate to the original page
        self.end_headers()

def main():
    try:
        port = 8080
        server = HTTPServer(('', port), WebServerHandler)
        print("Web server is running on port {}".format(port))
        server.serve_forever()

    except KeyboardInterrupt:
        print("^C entered, stopping web server...")
        server.socket.close()


if __name__ == '__main__':
    main()

关于python - 如何从 python 返回 HTTP 303?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37445901/

相关文章:

python - Argparse:预期一个参数

python - 从 os.walk 中有效地删除 dirnames 中的子目录

css - 如何在 GtkScrollbar 上设置最小宽度?

用于播放固定频率声音的 Python 库

python - 替换Excel表格中的数据

python - Katalon Export - 机器人框架问题

c - 为什么 PWD 为空以及如何修复它?

c++ - C语言写cgi代码

php - 共享主机环境中的 sys_get_temp_dir

python - 追加到数组[i](第一个元素)直到比较条件不再为真