How to Set Up a Simple HTTP Server for Local File Sharing with Python

razorfx9
4 min readJan 20, 2024

--

Introduction

Need to quickly share files across devices on your local network? Python’s built-in HTTP server functionality makes this a breeze. In this post, I’ll show you how to set up a basic HTTP server for local file sharing, making your files accessible from any device in your network.

What You’ll Need

  • Python installed on your computer. This script works with Python 3.
  • Basic knowledge of Python and your operating system’s command line.
  • Files you want to share placed in a specific directory.

Step-by-Step Guide

Step 1: The Python Script

First, let’s look at the script that will create our HTTP server.

import http.server
import socketserver
import os


PORT = 8000 # Feel free to use a different port
class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
def end_headers(self):
self.send_header('Access-Control-Allow-Origin', '*')
super().end_headers()
os.chdir('/path/to/your/files') # Replace with your directory path
handler_object = MyHttpRequestHandler
with socketserver.TCPServer(("", PORT), handler_object) as httpd:
print(f"Serving at port {PORT}")
print("Server is running. Press Ctrl+C to stop the server.")
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
print("Server stopped.")
httpd.server_close()
print("Server closed.")

At the bottom of the post I will go into depth about what each line in the above code means.

Step 2: Running the Script

  • Save the script in a file, say http_server.py.
  • Open a terminal or command prompt.
  • Navigate to the directory where you saved http_server.py.
  • Run the script using python http_server.py.

Step 3: Accessing Your Files

  • On another device in the same network, open a web browser.
  • Navigate to http://[Your-Computer's-IP-Address]:8000. Replace [Your-Computer's-IP-Address] with your actual IP address.

Step 4: Stopping the Server

  • When you’re done sharing files, go back to your terminal where the server is running.
  • Press Ctrl+C to stop the server.

Security and Best Practices

  • This server is intended for quick, local file sharing. Do not expose it to the public internet.
  • Ensure your firewall settings allow local network sharing.
  • Use this method within a trusted network as the server has minimal security features.

Bonus: One Line of Code

You can start a simple HTTP server in the current directory using just a single line of Python code. This method uses Python’s built-in HTTP server module. Here’s the one-liner you need:

python -m http.server 8765 # any port you want

Instructions:

  1. Open a terminal or command prompt.
  2. Navigate to the directory where you want to serve files from.
  3. Run the above command.

This will start an HTTP server on port 8765 serving the contents of the current directory. Just like the other server mentioned above, you can access the server from any device on your local network by navigating to http://[Your-Computer's-IP-Address]:8765. Replace [Your-Computer's-IP-Address] with the actual IP address of the computer where the server is running. When finished, just hitCtrl+C to stop the server.

Conclusion

Setting up a local HTTP server for file sharing can be extremely useful for quick, intra-network transfers. Python’s simplicity and versatility make tasks like these easy and efficient. Remember to follow security best practices and happy coding!

Breakdown of Code Snippet

Let’s break down the Python script to understand each part:

1. Import Statements:
`import http.server`: Imports Python’s built-in HTTP server module, which contains classes for implementing web servers.
`import socketserver`: Imports the `socketserver` module, which provides a framework for network servers.
— `import os`: Imports the `os` module, which allows interaction with the operating system, like changing the current working directory.

2. Setting the Port:
— `PORT = 8000`: This defines a variable `PORT` and assigns it the value `8000`. This is the port number on which your HTTP server will listen. You can change this number to any available port on your system.

3. Custom Request Handler Class:
— `class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler)`: This defines a custom request handler class, `MyHttpRequestHandler`, which inherits from `http.server.SimpleHTTPRequestHandler`. The `SimpleHTTPRequestHandler` class handles requests to serve files from the current directory or a specified directory.
— `def end_headers(self)`: This method is overridden from the parent class. It’s executed when ending the headers part of an HTTP response.
— `self.send_header(‘Access-Control-Allow-Origin’, ‘*’)`: Adds an HTTP header to allow Cross-Origin Resource Sharing (CORS). The `’*’` means that any origin is allowed. This is useful if your files need to be accessed from a webpage hosted on a different domain.
— `super().end_headers()`: Calls the `end_headers` method of the parent class to ensure that all headers are correctly ended.

4. Changing Working Directory:
— `os.chdir(‘/path/to/your/files’)`: Changes the current working directory of the script to the specified path. The HTTP server will serve files from this directory. You need to replace `’/path/to/your/files’` with the actual path where your files are located.

5. Creating the Server:
— `handler_object = MyHttpRequestHandler`: Creates an instance of the custom request handler class.
— `with socketserver.TCPServer((“”, PORT), handler_object) as httpd`: This line creates an instance of `TCPServer`, binding it to the specified PORT and using the custom handler. The empty string `””` means the server is accessible by any address the machine happens to have.
— `httpd.serve_forever()`: Starts the server, making it listen and respond to incoming requests indefinitely.
— `except KeyboardInterrupt`: This block allows the server to be stopped manually by pressing Ctrl+C in the command line.
— `httpd.server_close()`: Closes the server, releasing the port and any resources used.

6. Print Statements:
— The `print` statements provide feedback in the command line, indicating the server’s status (running, stopped, etc.).

--

--

No responses yet