html in do_GET() method of a simple Python webserver

Posted by Meeri_Peeri on Stack Overflow See other posts from Stack Overflow or by Meeri_Peeri
Published on 2011-06-30T06:50:23Z Indexed on 2011/06/30 8:22 UTC
Read the original article Hit count: 193

Filed under:
|
|
|

I am relatively new to Python but have been doing a lot of different things with it recently and I am liking it a lot. However, I ran into trouble/block with the following code.

import http.server
import socketserver
import glob
import random
class Server(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200, 'OK')
        self.send_header('Content-type', 'html')
        self.end_headers()
        self.wfile.write(bytes("<html> <head><title> Hello World </title> </head> <body>", 'UTF-8'))
        images = glob.glob('*.jpg')
        rand = random.randint(0,len(images)-1)
        imagestring = "<img src = \"" + images[rand] + "\" height = 1028 width = 786 align = \"right\"/> </body> </html>"
        self.wfile.write(bytes(imagestring, 'UTF-8'))

    def serve_forever(port):
        socketserver.TCPServer(('', port), Server).serve_forever()
if __name__ == "__main__":
    Server.serve_forever(8000)

What I am trying to do here is grab a random image from multiple images in the directory and add it into the response to a web request. The code works fine but when I access the server via browser, the image is not displayed. The html of the page is as intended though. The permissions on the files are 755. Also I tried to create an index.html file in the do_GET method. That didn't work either. I mean the index.html was generated fine, but the response in the browser this time did not show anything (not even the hello world in the title).

Am I missing anything very simple here? I was thinking should I overload the handle_request of the underlying SocketServer.BaseServer as the documentation says you should never override BaseHTTPServer's handle() method and should rather override the corresponding do_* method?

© Stack Overflow or respective owner

Related posts about python

Related posts about html