如何用Python内置http.server搭建可展示并访问目录图片的Web服务器
Absolutely! Python's built-in http.server module does exactly what you need out of the box—no extra libraries required. Here's how to make it work for your directory structure:
Basic Setup (No Custom Code Needed)
Your desired behavior is actually the default for http.server. Just follow these steps:
- Open a terminal and navigate to your
my_images/directory:cd /path/to/my_images - Start the server with one command:
- For Python 3:
python3 -m http.server 8000 - For Python 2 (if you still use it):
python -m SimpleHTTPServer 8000
- For Python 3:
- Open your browser and go to
http://localhost:8000. You'll see an index page titled Index of my_images with:- Clickable links to
img1.pngandimg2.png(clicking these will display the image directly in the browser) - A clickable link to
results/(navigating here will showresult.pngwith the same direct-access functionality)
- Clickable links to
Optional: Filter to Show Only Images (If Needed)
If you ever want to restrict the index to only show image files (hiding non-image files), you can create a custom handler by extending SimpleHTTPRequestHandler. Here's a quick example script (image_server.py):
from http.server import SimpleHTTPRequestHandler, HTTPServer import os import re class ImageOnlyHandler(SimpleHTTPRequestHandler): def list_directory(self, path): # Get the default directory listing response original_response = super().list_directory(path) if original_response is None: return None # Define allowed image extensions allowed_exts = ('.png', '.jpg', '.jpeg', '.gif', '.bmp') html_content = original_response.read().decode() # Filter out non-image file entries from the HTML filtered_html = re.sub( r'<li><a href="[^"]+\.(?!png|jpg|jpeg|gif|bmp)[^"]+">.*?</li>', '', html_content ) # Update the response with filtered content original_response.data = filtered_html.encode() original_response.headers['Content-Length'] = str(len(original_response.data)) return original_response if __name__ == '__main__': server_address = ('', 8000) httpd = HTTPServer(server_address, ImageOnlyHandler) print(f"Serving filtered images at http://localhost:8000") httpd.serve_forever()
Run this script from your my_images/ directory, and the index page will only display image files and subdirectories.
But for your original request, the basic server command is all you need—it's quick, simple, and does exactly what you described.
内容的提问来源于stack exchange,提问作者jvh

