webserver.py 2.27 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
import os
from http.server import HTTPServer, SimpleHTTPRequestHandler

HTTP_IP = '' # you can restrict the webserver to a specific IP, for security reasons
HTTP_PORT = 1111

IMAGE_FOLDER = 'html/images'

class MyHandler(SimpleHTTPRequestHandler):
	
	images = None
	
	def get_default_txt(self):
		all_files = os.listdir(IMAGE_FOLDER)
		self.images = []
		for f in all_files:
			if f[0:1] == '.':
				continue
			self.images.append( f )
		out = ""
		i = 0
		for im in self.images:
			out += '- <a href="' + str(i) + '">' + str(i) + '</a> : ' + im + '<br>'
			i += 1
		return out
	
	def page_image(self, imgid):
		path = self.images[ imgid ]
		path = os.path.join( IMAGE_FOLDER, path )
		out = '<a href="/">home</a><br/>'
		nextid = imgid + 1
		if nextid >= len(self.images):
			nextid = 0
		out += '<a href="' + str( nextid ) + '"><img src="' + path + '"/></a>'
		return out
	
	def stream_image( self, imgpath ):
		try:
			p = imgpath.lower()
			im_size = os.stat(imgpath).st_size
			im_data = open(imgpath, 'rb')
			self.send_response(200)
			if p.rfind('.jpg') or p.rfind('.jpeg'):
				self.send_header("Content-type", "image/jpg")
			elif p.rfind('.png'):
				self.send_header("Content-type", "image/png")
			elif p.rfind('.gif'):
				self.send_header("Content-type", "image/gif")
			self.send_header("Content-length", im_size)
			self.end_headers()
			self.wfile.write(im_data.read())
			im_data.close()
		except:
			self.send_error(404, "File not found")
		return
		
	def do_GET(self):
		
		print( self.path )
		
		req = self.path[1:].lower() 
		if req.rfind('.jpg') > 0 or req.rfind('.jpeg') > 0 or req.rfind('.png') > 0 or req.rfind('.gif') > 0:
			self.stream_image( self.path[1:] )
			return
		
		txt = ""
		
		req = self.path[1:]
		if req == '':
			txt = self.get_default_txt()
		else:
			if self.images == None:
				self.get_default_txt()
			try:
				imgid = int( req )
				if imgid < 0 or imgid >= len( self.images ):
					txt = self.get_default_txt()
				else:
					txt = self.page_image( imgid )
			except:
				txt = self.get_default_txt()
		
		self.send_response(200)
		self.send_header('Content-Type', 'text/html')
		self.end_headers()
		self.wfile.write(txt.encode("utf-8"))

SERVER = HTTPServer((HTTP_IP, HTTP_PORT), MyHandler)

print( "running server on %s:%s" % ( HTTP_IP, HTTP_PORT ) )

SERVER.serve_forever()