Python 3.x BaseHTTPServer or http.server

后端 未结 4 1036
一向
一向 2021-01-30 12:26

I am trying to make a BaseHTTPServer program. I prefer to use Python 3.3 or 3.2 for it. I find the doc hard to understand regarding what to import but tried changing the import

4条回答
  •  旧巷少年郎
    2021-01-30 13:18

    Your program in python 3.xx does work right out of the box - except for one minor problem. The issue is not in your code but the place where you are writing these lines:

    self.wfile.write("Hello World !")
    

    You are trying to write "string" in there, but bytes should go there. So you need to convert your string to bytes.

    Here, see my code, which is almost same as you and works perfectly. Its written in python 3.4

    from http.server import BaseHTTPRequestHandler, HTTPServer
    import time
    
    hostName = "localhost"
    hostPort = 9000
    
    class MyServer(BaseHTTPRequestHandler):
        def do_GET(self):
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            self.wfile.write(bytes("Title goes here.", "utf-8"))
            self.wfile.write(bytes("

    This is a test.

    ", "utf-8")) self.wfile.write(bytes("

    You accessed path: %s

    " % self.path, "utf-8")) self.wfile.write(bytes("", "utf-8")) myServer = HTTPServer((hostName, hostPort), MyServer) print(time.asctime(), "Server Starts - %s:%s" % (hostName, hostPort)) try: myServer.serve_forever() except KeyboardInterrupt: pass myServer.server_close() print(time.asctime(), "Server Stops - %s:%s" % (hostName, hostPort))

    Please notice the way I convert them from string to bytes using the "UTF-8" encoding. Once you do this change in your program, your program should work fine.

提交回复
热议问题