2

This question comes from this one.

What I want is to be able to return the HTTP 303 header from my python script, when the user clicks on a button. My script is very simple and as far as output is concerned, it only prints the following two lines:

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

I have also tried many different variants of the above (with a different number of \r and \n at the end of the lines), but without success; so far I always get Internal Server Error.

Are the above two lines enough for sending a HTTP 303 response? Should there be something else?

3
  • Have you read stackoverflow.com/q/6122957/3001761? Commented May 25, 2016 at 19:36
  • Thanks John! Yes, I have, but it doesn't solve my problem. Instead of Internal Server Error I get a page containing the text Location: http://192.168.1.109, instead of being redirected to that page. Commented May 25, 2016 at 20:12
  • So I had a look at the apache error log and I see that there's no error when the first line is Status: 303 See other\n. So this other question is right in this part. The second line (Location: ...), however, doesn't appear to work... Commented May 25, 2016 at 20:35

3 Answers 3

3

Assuming you are using cgi (2.7)(3.5)

The example below should redirect to the same page. The example doesn't attempt to parse headers, check what POST was send, it simply redirects to the page '/' when a POST is detected.

# 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()
Sign up to request clarification or add additional context in comments.

12 Comments

Thanks Michal! I'm getting an error though :( name 'self' is not defined. I am using python2.
@panos , this is a more self(haha) contained example of what you are trying to accomplish.
@panos it should be python two compatible now
Thanks man! I'm trying to make it work but I get IndentationError: at the first if... And since I'm a python newbie I don't really know where to put the indent...
@panos Try it now.
|
0

Typically browsers like to see /r/n/r/n at the end of an HTTP response.

Comments

0

Be very careful about what Python automatically does. For example, in Python 3, the print function adds line endings to each print, which can mess with HTTP's very specific number of line endings between each message. You also still need a content type header, for some reason.

This worked for me in Python 3 on Apache 2:

print('Status: 303 See Other')
print('Location: /foo')
print('Content-type:text/plain')
print()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.