假设您使用的是 cgi ( 2.7 )( 3.5 )
下面的示例应重定向到同一页面。该示例不会尝试解析标头,检查发送了什么 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()