I have an index.html and a 404.html, when I do python -m http.server the 404.html page isn't used, how do I fix that?
Assistant
When you use Python's built-in HTTP server (using python -m http.server), it does not automatically use a custom 404.html page for handling 404 errors. The default http.server module does not have this functionality built-in.
To serve a custom 404 error page, you'll need to create a custom server implementation. Here's one way to do it using Python's module by extending the class:
User
When I run python custom_server.py in linux the execution stops shortly after, why?
Assistant
http.server
SimpleHTTPRequestHandler
Create a Python script (e.g., custom_server.py) with the following content:
python
import http.server
import os
class CustomHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
def send_error(self, code, message=None, explain=None):
if code == 404:
self.send_response(code, message)
self.send_header("Content-Type", self.error_content_type)
self.end_headers()
if os.path.exists('404.html'):
with open('404.html', 'rb') as file:
self.copyfile(file, self.wfile)
else:
self.wfile.write(b"404 - File Not Found")
else:
super().send_error(code, message, explain)
if __name__ == '__main__':
PORT = 8000
server_address = ('', PORT)
httpd = http.server.HTTPServer(server_address, CustomHTTPRequestHandler)
print(f"Serving on port {PORT}")
httpd.serve_forever()
Run the custom server script:
sh
python custom_server.py
This custom server will listen on port 8000, and when a 404 error occurs, it will serve the 404.html file if it exists in the same directory.
The send_error method is overridden to check if the error code is 404.
If a 404 error occurs, it sends the content of 404.html. If 404.html does not exist, it sends a simple "404 - File Not Found" message.
The script sets up and starts an HTTP server using the custom request handler.
Feel free to modify the script according to your needs, such as changing the port number or enhancing the error handling logic.
If the custom server script stops shortly after execution, it might be due to an unhandled exception or some other issue in the script. Let's add some debugging information to help identify the problem.
First, ensure that you have the necessary permissions to run the script and that no other process is using the specified port (default is 8000).
Here's an updated version of the script with added error handling and logging:
python
import http.server
import os
import logging
class CustomHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
def send_error(self, code, message=None, explain=None):
if code == 404:
self.send_response(code, message)
self.send_header("Content-Type", self.error_content_type)
self.end_headers()
if os.path.exists('404.html'):
with open('404.html', 'rb') as file:
self.copyfile(file, self.wfile)
else:
self.wfile.write(b"404 - File Not Found")
else:
super().send_error(code, message, explain)
if __name__ == '__main__':
PORT = 8000
server_address = ('', PORT)
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
try:
httpd = http.server.HTTPServer(server_address, CustomHTTPRequestHandler)
logger.info(f"Serving on port {PORT}")
httpd.serve_forever()
except Exception as e:
logger.error(f"Server error: {e}")
except KeyboardInterrupt:
logger.info("Server stopped by user")
finally:
if 'httpd' in locals():
httpd.server_close()
logger.info("Server closed")
This script includes logging to help you identify any issues that might be causing the server to stop. Here's what it does:
Sets up basic logging to log information and errors.
Wraps the server setup and execution in a try block to catch and log any exceptions.
Adds a finally block to ensure the server is properly closed if an exception occurs or if the server is stopped by the user (e.g., by pressing Ctrl+C).
To run the script, use the following command:
sh
python custom_server.py
If the server stops shortly after execution, check the console output for any logged errors. This should give you more information about what went wrong.
Additionally, ensure that:
The 404.html file exists in the same directory as the script.
No other process is using port 8000. You can change the port number by modifying the PORT variable if needed.