3
votes

I'm learning about full stacks development of Udacity and we have to create a simple python server using http.server.

I wrote a small program in python that does a GET request very well. I'm having issues with the post. The server is running on port 8080, local host. Any POST request i give is returning a 501 unsupported method error. I'm mostly into kernel device drivers etc and I'm not used to debugging errors like this.

The program is creating a simple server that prints a greet message on GET request as such. http:localhost:8080/hello It also gives the user a form to enter a new greeting message, but when entered, give the 501 error. The POST method is supposed to display the same page with the user inputted greeting. I' using CGI to get this done.

I'm stuck! Also, if anyone can provide links/tips to how to go about debugging such things, i'd be grateful! Is there like a log file i can read or something?

The program:

from http.server import BaseHTTPRequestHandler, HTTPServer
import cgi


class WebServerHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        if self.path.endswith("/hello"):
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            output = ""
            output += "<html><body>"
            output += "<h2> How's it going?</h2>"
            output += "<form method = 'POST' enctype='multipart/form-data' action='/hello'> What would you like me to say?</h2><input name = 'message' type = 'text'> <input type = 'submit' value = 'Submit'></form>"
            output += "</body></html>"
            self.wfile.write(output.encode(encoding='utf_8'))
            print (output)
            return
        if self.path.endswith("/hola"):
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            output = ""
            output += "<html><body>&#161hola  <a href = /hello> Back to English! </a>"
            output += "<form method = 'POST' enctype='multipart/form-data' action='/hello'> What would you like me to say?</h2><input name = 'message' type = 'text'> <input type = 'submit' value = 'Submit'></form>"
            output += "</body></html>"
            self.wfile.write(output.encode(encoding='utf_8'))
            print (output)
            return

        else:
            self.send_error(404, 'File Not Found:')


def do_POST(self):
        try:
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            ctype, pdict = cgi.parse_header(
                self.headers.getheader('content-type'))
            if ctype == 'multipart/form-data':
                fields = cgi.parse_multipart(self.rfile, pdict)
                messagecontent = fields.get('message')
            output = ""
            output += "<html><body>"
            output += " <h2> Okay, how about this: </h2>"
            output += "<h1> %s </h1>" % messagecontent[0]
            output += '''<form method='POST' enctype='multipart/form-data' action='/hello'><h2>What would you like me to say?</h2><input name="message" type="text" ><input type="submit" value="Submit"> </form>'''
            output += "</body></html>"
            self.wfile.write(output.encode(encoding = "utf_8"))
            print (output)
        except:
            pass




def main():
    try:
        port = 8080
        server = HTTPServer(('', port), WebServerHandler)
        print ("Web Server running on port: 8080")
        server.serve_forever()
    except KeyboardInterrupt:
        print (" ^C entered, stopping web server....")
        server.socket.close()

if __name__ == '__main__':
    main()
1
docs.python.org/3/library/… As you can see in that link do_POST is not supported by your class. I believe that might be the error. Error 501, “Can only POST to CGI scripts”, is output when trying to POST to a non-CGI url - Aquiles
Thanks for that! I've been trying to fix it but i don't know where to begin. Any help would be appreciated :D - Rahul Raghunath
I don't know much about that server, I used to use cherrypy which is good and easy to use, and if you want to set a small server Flask or Bottle are great for that. Those are web frameworks for python - Aquiles

1 Answers

0
votes

Your do_POST function is not indented properly, it's outside the class right now, have it aligned with the do_GET function and it should be fine.