Python Basehttprequesthandler - How to insert correct image path

Asked

Viewed 23 times

-2

When I create a Web application in python, but without using Frameworks, just using the Httpserver and Basehttprequesthandler classes, how do I insert an image? That is the code:

https://pastebin.com/W6iPK2P2

In the same directory as my PY file, I have an img folder with the image inside. However, the image does not appear. How should be my variable 'image' for the image to appear correctly?

1 answer

-1


Good morning. vc has to do a validation of the extension of the files to return the correct minetype follows an ex taken from the net that works:

#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep

PORT_NUMBER = 8080

#This class will handles any incoming request from
#the browser 
class myHandler(BaseHTTPRequestHandler):
    
    #Handler for the GET requests
    def do_GET(self):
        if self.path=="/":
            self.path="/index_example2.html"

        try:
            #Check the file extension required and
            #set the right mime type

            sendReply = False
            if self.path.endswith(".html"):
                mimetype='text/html'
                sendReply = True
            if self.path.endswith(".jpg"):
                mimetype='image/jpg'
                sendReply = True
            if self.path.endswith(".gif"):
                mimetype='image/gif'
                sendReply = True
            if self.path.endswith(".js"):
                mimetype='application/javascript'
                sendReply = True
            if self.path.endswith(".css"):
                mimetype='text/css'
                sendReply = True

            if sendReply == True:
                #Open the static file requested and send it
                f = open(curdir + sep + self.path) 
                self.send_response(200)
                self.send_header('Content-type',mimetype)
                self.end_headers()
                self.wfile.write(f.read())
                f.close()
            return


        except IOError:
            self.send_error(404,'File Not Found: %s' % self.path)

try:
    #Create a web server and define the handler to manage the
    #incoming request
    server = HTTPServer(('', PORT_NUMBER), myHandler)
    print 'Started httpserver on port ' , PORT_NUMBER
    
    #Wait forever for incoming htto requests
    server.serve_forever()

except KeyboardInterrupt:
    print '^C received, shutting down the web server'
    server.socket.close()
    

source: https://github.com/tanzilli/playground/blob/master/python/httpserver/example2.py

another way is to return the jpg as binary in the image endswitch would look like this for jpg

if self.path.endswith(".jpg"):
    f = open(applicationPath + '/' + self.path, 'rb')
    self.send_response(200)
    self.send_header('Content-type','image/jpg')
    self.end_headers()
    self.wfile.write(f.read())
    f.close()
    return
  • But my intention is not to bring the image directly. After that I will use HTML templates, so I need to bring a normal HTML content that has an 'img' tag. So in this case I’m not sure what to put in the property 'src' for the image to be loaded.

  • So the first ex I sent you works that way. it will only process the extension of the file to return the correct mimetype and you can insert the image in your html

  • 1

    True, I didn’t understand. I had to make some modifications to run in Python 3, but it worked! I also had to make a condition for when it is HTML, because then Jinja has to process the template. But in the end it worked. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.