Spaces:
Sleeping
Sleeping
File size: 2,171 Bytes
e9e471e | 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 | #!/usr/bin/env python3
"""
Simple HTTP server to display images with shorter names
"""
import http.server
import socketserver
import webbrowser
import os
from pathlib import Path
def start_image_server(port=8080):
"""Start a simple HTTP server to display images"""
# Change to the directory containing our files
os.chdir(Path(__file__).parent)
# Create a custom handler that serves files
class ImageHandler(http.server.SimpleHTTPRequestHandler):
def end_headers(self):
# Add CORS headers to allow cross-origin requests
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
self.send_header('Access-Control-Allow-Headers', 'Content-Type')
super().end_headers()
try:
with socketserver.TCPServer(("", port), ImageHandler) as httpd:
print(f"π Image server starting on port {port}")
print(f"π Serving files from: {os.getcwd()}")
print(f"π Open your browser to: http://localhost:{port}")
print(f"π Main display: http://localhost:{port}/short_image_display.html")
print(f"π§ͺ Test display: http://localhost:{port}/image_display_test.html")
print(f"\nPress Ctrl+C to stop the server")
# Try to open browser automatically
try:
webbrowser.open(f"http://localhost:{port}/short_image_display.html")
except:
pass
httpd.serve_forever()
except KeyboardInterrupt:
print(f"\nπ Server stopped")
except OSError as e:
if e.errno == 48: # Address already in use
print(f"β Port {port} is already in use. Try a different port:")
print(f" python3 simple_image_server.py {port + 1}")
else:
print(f"β Error starting server: {e}")
if __name__ == "__main__":
import sys
# Get port from command line argument or use default
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8080
start_image_server(port)
|