You can set up a local HTTP server using Python with the following steps:
Using Python 3
-
Open a terminal.
-
Navigate to the directory where you want to serve files. For example:
cd /path/to/your/directory -
Start the HTTP server:
python3 -m http.server 8000This command will start a simple HTTP server on port 8000.
-
Access the server: Open a web browser and go to
http://localhost:8000to see the files in the directory.
Setting Up Basic Authentication (Optional)
If you want to implement basic authentication, you can use the http.server module along with http.server.SimpleHTTPRequestHandler. Here’s a basic example:
-
Create a file named
server.pywith the following content:from http.server import HTTPServer, SimpleHTTPRequestHandler from urllib.parse import urlparse import base64 class AuthHandler(SimpleHTTPRequestHandler): def do_AUTHHEAD(self): self.send_response(401) self.send_header('WWW-Authenticate', 'Basic realm=\"Test\"') self.send_header('Content-type', 'text/html') self.end_headers() def do_GET(self): if self.headers.get('Authorization') is None: self.do_AUTHHEAD() self.wfile.write(b'Unauthorized') else: auth = self.headers['Authorization'] username, password = base64.b64decode(auth.split(' ')[1]).decode().split(':') if username == 'your_username' and password == 'your_password': SimpleHTTPRequestHandler.do_GET(self) else: self.do_AUTHHEAD() self.wfile.write(b'Unauthorized') httpd = HTTPServer(('localhost', 8000), AuthHandler) httpd.serve_forever() -
Run the server:
python3 server.py -
Access the server: Go to
http://localhost:8000in your web browser. You will be prompted for a username and password.
Note
Make sure to replace your_username and your_password with your desired credentials.
This setup allows you to serve files locally and test basic authentication.
