65 lines
1.7 KiB
Python
65 lines
1.7 KiB
Python
|
from http.server import BaseHTTPRequestHandler
|
||
|
from urllib.request import urlopen
|
||
|
from urllib.error import URLError
|
||
|
from socket import error, timeout
|
||
|
from io import BytesIO
|
||
|
from time import sleep
|
||
|
|
||
|
from classes.image import Image
|
||
|
from static import START_HEADERS, PART_BOUNDARY
|
||
|
|
||
|
class ImageHandler(BaseHTTPRequestHandler):
|
||
|
def __init__(self, source, fallback, *args, **kwargs):
|
||
|
self.source_image = source
|
||
|
self.fallback_image = fallback
|
||
|
super().__init__(*args, **kwargs)
|
||
|
|
||
|
def get_next_image(self):
|
||
|
try:
|
||
|
bfr = BytesIO()
|
||
|
src = urlopen(self.source_image).read()
|
||
|
bfr.write(src)
|
||
|
bfr.seek(0)
|
||
|
img = Image.open(bfr)
|
||
|
except:
|
||
|
with open(self.fallback_image, "rb") as infile:
|
||
|
bfr = BytesIO()
|
||
|
src = infile.read()
|
||
|
bfr.write(src)
|
||
|
bfr.seek(0)
|
||
|
img = Image.open(bfr)
|
||
|
|
||
|
return img
|
||
|
|
||
|
def send_image(self, image=None):
|
||
|
image = image or self.get_next_image()
|
||
|
|
||
|
self.end_headers()
|
||
|
self.wfile.write(PART_BOUNDARY.encode("utf-8"))
|
||
|
self.end_headers()
|
||
|
|
||
|
data, headers = image.prepare_sending()
|
||
|
|
||
|
for key, value in headers.items():
|
||
|
self.send_header(key, value)
|
||
|
|
||
|
self.end_headers()
|
||
|
|
||
|
self.wfile.write(data)
|
||
|
|
||
|
def do_GET(self):
|
||
|
if not self.path == "/":
|
||
|
self.send_response_only(404)
|
||
|
return
|
||
|
|
||
|
self.send_response(200)
|
||
|
|
||
|
for key, value in START_HEADERS.items():
|
||
|
self.send_header(key, value)
|
||
|
|
||
|
try:
|
||
|
while True:
|
||
|
self.send_image()
|
||
|
sleep(5)
|
||
|
except:
|
||
|
pass
|