1

I'm using the below code to display my images in browser.

import os, time
from glob import glob
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer

boundary = '--boundarydonotcross'


def request_headers():
    return {
        'Cache-Control': 'no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0',
        'Connection': 'close',
        'Content-Type': 'multipart/x-mixed-replace;boundary=%s' % boundary,
        'Expires': 'Mon, 3 Jan 2000 12:34:56 GMT',
        'Pragma': 'no-cache',
    }


def image_headers(filename):
    return {
        'X-Timestamp': time.time(),
        'Content-Length': os.path.getsize(filename),
        # FIXME: mime-type must be set according file content
        'Content-Type': 'image/jpeg',
    }


# FIXME: should take a binary stream
def image(filename):
    with open(filename, "rb") as f:
        # for byte in f.read(1) while/if byte ?
        byte = f.read(1)
        while byte:
            yield byte
            # Next byte
            byte = f.read(1)


# Basic HTTP server
class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        # Response headers (multipart)
        for k, v in request_headers().items():
            self.send_header(k, v)
        # Multipart content
        while True:
            for filename in glob('img/*'):
                # Part boundary string
                self.end_headers()
                self.wfile.write((boundary).encode())
                self.end_headers()
                # Part headers
                for k, v in image_headers(filename).items():
                    self.send_header(k, v)
                self.end_headers()
                # Part binary
                for chunk in image(filename):
                    self.wfile.write(chunk)

    def log_message(self, format, *args):
        return


httpd = HTTPServer(('', 8001), MyHandler)
httpd.serve_forever()

However, I'm unable to use this for multiple clients. i.e., When I hit localhost:8001 in my browser, it works as I expected. But I doesn't work if I open a new tab and hit localhost:8001. It's basically not allowing me to use the requested resource.

Any help would be appreciable.

Mohamed Thasin ah
  • 10,754
  • 11
  • 52
  • 111
  • As the red banner in the docs says, that isn't intended for production use. – jonrsharpe Sep 30 '19 at 09:53
  • Basic HTTP server can only handle one request at a time so if the first request isn't finished. a second won't be treated. Perhaps you want to add threading? https://stackoverflow.com/questions/14088294/multithreaded-web-server-in-python#14089457 – gelonida Sep 30 '19 at 10:45

0 Answers0