How to serve static files?

To serve static files using the http.server module in Python, you can use the built-in SimpleHTTPRequestHandler, which is designed for this purpose. Here’s how you can do it:

Basic Example

You can start a simple HTTP server that serves static files from the current directory by running the following command in your terminal:

python3 -m http.server 8000

This command will serve files from the current directory on port 8000. You can access the files by navigating to http://localhost:8000 in your web browser.

Custom Server for Static Files

If you want to create a custom server in a Python script, you can do so as follows:

from http.server import SimpleHTTPRequestHandler, HTTPServer

class CustomHandler(SimpleHTTPRequestHandler):
    def end_headers(self):
        # You can add custom headers here if needed
        self.send_header('Access-Control-Allow-Origin', '*')
        super().end_headers()

def run(server_class=HTTPServer, handler_class=CustomHandler, port=8000):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print(f'Serving static files on port {port}...')
    httpd.serve_forever()

if __name__ == "__main__":
    run()

Explanation:

  • CustomHandler: This class inherits from SimpleHTTPRequestHandler. You can override methods like end_headers to add custom headers if needed.
  • run function: This function sets up and starts the HTTP server on the specified port.

Serving Files from a Specific Directory

If you want to serve files from a specific directory, you can change the working directory in your script before starting the server:

import os
from http.server import SimpleHTTPRequestHandler, HTTPServer

class CustomHandler(SimpleHTTPRequestHandler):
    pass  # You can customize this handler as needed

def run(directory, server_class=HTTPServer, handler_class=CustomHandler, port=8000):
    os.chdir(directory)  # Change to the specified directory
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print(f'Serving static files from {directory} on port {port}...')
    httpd.serve_forever()

if __name__ == "__main__":
    run('path/to/your/static/files')  # Replace with your directory path

Accessing Static Files

Once the server is running, you can access your static files by navigating to http://localhost:8000/yourfile.ext in your web browser, where yourfile.ext is the name of the file you want to access.

0 Comments

no data
Be the first to share your comment!